I'm new to React and I'm getting this error:
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
From what I understand, it appears as though I have a memory leak and need a useEffect cleanup for my useCallback hook?
I have tried adding a useRef
to check mount but the return doesn't change the state to false.
const MyComponent = ({data}) => {
const mounted = useRef(true);
const [loading, setLoading] = useState(false);
const isLoading = useCallback(async () => {
setLoading(true);
if (data) {
console.log('YAY DATA: ', data);
}
return () => {
setLoading(false); // unreachable code
mounted.current = false; // does this do the cleanup?
};
}, [loading]);
return (
//...some component
);
};
export default MyComponent;