BarakOren
BarakOren

Reputation: 109

cleanup useEffect when component UnMounts

i get the message:
"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."

i have a function that checks the user scroll position, that causes this problem. but i cant figure out how to stop it.

const [position, setPosition] = useState(null);

    useEffect(() => {
    window.onscroll = () => {
        if(window.pageYOffset > 100){
            setPosition(true);
        } else if (window.pageYOffset < 100) {
            setPosition(false);
        }
    } 
},[])

any ideas? thank guys!

Upvotes: 1

Views: 105

Answers (1)

vitoke
vitoke

Reputation: 748

A useEffect cleanup function is a function that you return from the call to useEffect that cleans up anything that might still cause, for example, state changes. It would probably look like this:

const [position, setPosition] = useState(null);

useEffect(() => {
    window.onscroll = () => {
        if(window.pageYOffset > 100){
            setPosition(true);
        } else if (window.pageYOffset < 100) {
            setPosition(false);
        }
    }

    return () => {
        // whatever needs to be done to remove the onscroll listener
        window.onscroll = undefined
    } 
}, [])

Upvotes: 2

Related Questions