This is my state:
const [time, setTime] = useState(10)
And this is my handler:
const runTimer = () => {
useEffect(() => {
const interval = setInterval(() => {
console.log(time)
if (time > 0) {
setTime(time - 1)
} else {
console.log("End")
}
}, 1000);
return () => clearInterval(interval)
}, [])
}
My log:
9
9
9
9
9
.
.
.
Why setTime
doesn't work ?
time
variable most increase per 1000 delay
CodePudding user response:
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, setTimer] = 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>
}