'Any downside or ill effects of using useAbortableState instead of useState [custom hook] in React?
I am way too irritated with the warning: cannot update state on unmounted component. And I have been using logic like:
const [mounted,setMounted] = useState(true);
useEffect(() => {
return () => setMounted(false);
},[]);
if(mounted) setState(<newValue>);
Now these if statements are increasing in lots of places and so I decided to go with a custom hook as shown below:
import { useState, useEffect, useCallback } from 'react';
const useAbortableState = <T,>(initialValue: T): [T, (value: T) => void] => {
const [value, setValue] = useState(initialValue);
const [mounted, setMounted] = useState(true);
useEffect(() => {
return () => setMounted(false);
}, []);
const setNewValue = useCallback(
(newValue: any) => {
if (mounted) {
setValue(newValue);
}
},
[mounted]
);
return [value, setNewValue];
};
export default useAbortableState;
I am missing any performance stuff or some side effects which could be dangerous in this case. Can any expert confirm if I could use useAbortableState instead of useState everywhere in my components for state updates or should I go with useState with the mounted logic to play safe?
Also even though I am using the custom logic, I still get the cannot update state on unmounted component warning. I am not sure what I could be missing here?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
