I've learned that to prevent memory leaks, I'm supposed to clean up after useEffect hooks which call async functions to update state.
I have found a couple of solutions for this;
First one, to use a simple, boolean variable:
useEffect(() => {
let isSubscribed = true;
const runEffect = async () => {
const data = await getSomething();
isSubscribed && setState(data)
};
runEffect();
return () => {
isSubscribed = false;
};
}, []);
And this method using the useRef hook:
const _isMounted = useRef(true);
useEffect(() => {
const runEffect = async () => {
const data = await getSomething();
_isMounted.current && setState(data)
};
runEffect();
return () => {
_isMounted.current = false;
}
}, []);
Is there a big enough difference between the two methods? If so, which is better?