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 ?
You are not really removing the interval. Your
handleSlide
function registers an anonymoussetInterval
. You can clear it by callingclearInterval
. However you need to pass an ID for that which is conveniently returned bysetInterval
.Your code could look like this
and then in your callback
You need to store and clear the interval:
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.