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?
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With