Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do you need to use clearInterval to reset the timer in React?

In the following code:

  useEffect(() => {
    const interval = setInterval(() => {
      setSeconds(seconds => seconds + 1);
    }, 1000);
    return () => clearInterval(interval);
  }, []);
  

Why do you need to return a cleanup function that resets the interval object? In my understanding, since the interval function object was not created with useCallback(), the function should be re-initialized with each render and therefore have no memory of past interval values. Why is a cleanup function needed to clear it before the next render?

like image 522
John Jacob Avatar asked Sep 20 '25 08:09

John Jacob


1 Answers

Why is a cleanup function needed to clear it before the next render?

(emphasis mine)

It's not and it's not what this code does.

By passing an empty dependency list to useEffect ([]) you are effectively telling React to only run this hook the first time the component renders, not(!) every time the component re-renders.

Now, clearing the interval when the component gets unmounted/destroyed (which is what this code does) is necessary, otherwise the interval would keep running (and throw an error eventually since you cannot update the state of an unmounted component).

like image 171
Felix Kling Avatar answered Sep 22 '25 22:09

Felix Kling



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!