Closed devYuraKim closed 2 months ago
clearInterval
function Timer({ dispatch, time }) {
useEffect(
function () {
const timer = setInterval(() => dispatch({ type: "countdown" }), 1000);
return () => {
clearInterval(timer);
};
},
[dispatch]
);
return <div className="timer">{time}</div>;
}
Problem: Double Invocation of useEffect
Without a cleanup function, here's what happens:
useEffect
sets an interval once during the first run.useEffect
a second time (due to StrictMode
), which sets another interval without clearing the first one.Solution: clearInterval
The cleanup function ensures that when useEffect
runs for the second time, it clears the first interval before setting up a new one. Here's the process:
useEffect
runs, it sets an interval and returns a cleanup function.React.StrictMode
causes a second invocation, the cleanup function is executed first, clearing the first interval.
I'm suspecting
React.StrictMode
and when I commented it out, timer did work normally. However, I think it's more of a workaround than a solution.index.js
App.js
Timer.js