Nextjs: update state not work in interval
The function you pass to useEffect
has closed over the timer
variable from the first time the component rendered.
Each time the component renders, the current value of the state is read and a timer
variable is created with that value.
You aren't accessing that variable though. The variable
you are accessing on the interval never changes, so every time you access it, it is still 10
.
State functions are passed the current value as an argument, so use that instead.
const Timer = () => {
const [timer, setTime] = useState(10);
useEffect(() => {
const interval = setInterval(() => {
setTime(
(currentTime) => {
if (currentTime > 0) {
return currentTime - 1;
} else {
console.log(end);
clearInterval(interval);
return currentTime;
}
}
);
}, 1000);
return () => clearInterval(interval)
}, [])
return <p>{timer}</p>
}