Search code examples
javascriptreactjsevent-listener

removeEventListener doesn't work inside useEffect logic


In ReactJS, if I have a useEffect checking for an observer like this:

// ...observer code here

useEffect(() => {

    function handleParallax() {
        let items = document.querySelectorAll('.item')
        items.forEach(item => {
            let distance = (window.scrollY || window.pageYOffset),
                distanceFinal = item.parentNode.offsetTop - distance,
                multi = 45;
            console.log((distanceFinal * multi)/500);
            let calc = `translate3d(0, calc(370px + ${((distanceFinal * multi)/500)}px), 0)`;
            item.setAttribute('style',
                `transform: ${calc};
                -ms-transform: ${calc};
                -webkit-transform: ${calc};`
            );
        });
    }

    if (isIntersecting) {
        console.log('enter')
        window.addEventListener('scroll', handleParallax, true)
    }else{
        console.log('exit')
        window.removeEventListener('scroll', handleParallax, true);
    }
}, [isIntersecting]);

the removeEventListener doesn't work, in fact I receive a console log in browser of the enter/exit state of the observed area, but the console log inside the handleParallax function still logs as I scroll outside of the observer bounds, why is that?


Solution

  • Move the handleParallax function outside the component (which is possible since it doesn't use any internal component data), so that the same reference will be passed to both addEventListener and removeEventListener.