I am making a timer in a Tenzie game. When a user clicks a button, onClick function sets the isTimerActive state to true which was initially false and tenzie state is also false to default and when user complete the game tenzie state sets to true.
React.useEffect(() => {
let timer = null;
if(isTimerActive && !tenzie){
timer = setInterval(() => {
setTime(prevSecond => prevSecond + 1);
}, 1000);
}
return () => {
clearInterval(timer);
}
}, [tenzie, isTimerActive])
I want to know when React runs this cleanup function and if it runs it every time it runs useEffect then why my timer is working ?
Here the simple answer is cleanup function of useEffect runs only when the component gets unmount, it never runs each the useEffect's callback gets executed, it only runs if your component is getting un-mount.
Reff docs: https://reactjs.org/docs/hooks-reference.html#cleaning-up-an-effect
Its good to have cleanup function for these scenario (as you are using setInterval) because you don't want setInterval to call even after you component gets unmount. So its better to clear the interval in the clean up function before un mounting the component.