Open gaeaehrlich opened 2 years ago
Hey @gaeaehrlich 👋
I agree that the implementation is broken, but there's an easy fix. We just need to return a function instead of the value itself:
const useUnmounted = () => {
const unmounted = useRef(false);
useEffect(() => () => {unmounted.current = true}, []);
return useCallback(() => unmounted.current, []);
};
That way you always get the latest value. Now your example can be changed as follows:
// Instead of
!unmounted && setState('no text')
// Do
!unmounted() && setState('no text')
useMounted
Explanation
Code example
What is the expected behavior? When using
useUnmounted
the returned value should be true if component has unmounted.What is happening instead? The value remains false.
What error message are you getting? 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.