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 ?

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

Leave a Comment