Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useUnmounted does not work correctly #77

Open
gaeaehrlich opened this issue Feb 7, 2022 · 1 comment
Open

useUnmounted does not work correctly #77

gaeaehrlich opened this issue Feb 7, 2022 · 1 comment
Labels
bug Something isn't working

Comments

@gaeaehrlich
Copy link
Contributor

gaeaehrlich commented Feb 7, 2022

useMounted

Explanation

Code example

const Element = () => {
    const [state, setState] = useState('text');
    const unmounted = useUnmounted();

    useEffect(() => {
        setTimeout(() => {
            !unmounted && setState('no text')
        }, 6000);
    }, [unmounted, state])

    return <div>{state}</div>
}

export default () => {
    const [mount, setMount] = useState(true);
    setTimeout(() => setMount(false), 5000);

    return <>{mount && <Element/>}</>
}
  • 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.

@gaeaehrlich gaeaehrlich added the bug Something isn't working label Feb 7, 2022
gaeaehrlich added a commit to gaeaehrlich/webrix that referenced this issue Feb 7, 2022
gaeaehrlich added a commit to gaeaehrlich/webrix that referenced this issue Feb 7, 2022
@ykadosh
Copy link
Collaborator

ykadosh commented Feb 7, 2022

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')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

2 participants