How to remove event listener on component unmount react js?

I’m console logging every 2 seconds in handleSlide function and I want it to run everytime the component mounts .

    const handleSlide = () => {
        setInterval(() => {
            console.log('runs');
        }, 2000);
    };

    useEffect(() => {
        window.addEventListener('load', handleSlide);
        return () => {
            return window.removeEventListener('load', handleSlide);
        };
    }, []);

The problem is the handleSlide function still runs after unmount and I see the console log on other pages and components as well .

How can I remove event listener in react js when component unmounts ?

3 thoughts on “How to remove event listener on component unmount react js?”

  1. You are not really removing the interval. Your handleSlide function registers an anonymous setInterval. You can clear it by calling clearInterval. However you need to pass an ID for that which is conveniently returned by setInterval.

    Your code could look like this

    yourID = setInterval(() => {
                console.log('runs');
            }, 2000);
    

    and then in your callback

    clearInterval(yourID)
    
    Reply
  2. You need to store and clear the interval:

    let interval;
    const handleSlide = () => {
        interval = setInterval(() => {
            console.log('runs');
        }, 2000);
    };
    
    useEffect(() => {
        window.addEventListener('load', handleSlide);
        return () => {
            clearInterval(interval)
        };
    }, []);
    
    Reply
  3. you are using setInterval and it runs every 2 seconds when it is mounting. you need a callback function to clear it at certain condition. either your interval runs every 2 seconds.

    Reply

Leave a Comment