0

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 an event listener in reactjs when a component unmounts ?

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.