open-amdocs / webrix

Powerful building blocks for React-based web applications
https://webrix.amdocs.com
Apache License 2.0
431 stars 31 forks source link

useUnmounted does not work correctly #77

Open gaeaehrlich opened 2 years ago

gaeaehrlich commented 2 years ago

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/>}</>
}
ykadosh commented 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')