I want to have a countdown timer that counts from 60 to zero when the stage of program reaches two. Here's my code:
const [timer, setTimer] = useState(60)
useEffect(() => {
if (stage === 2) {
const interval = setInterval(() => {
console.log(timer)
setTimer(timer - 1)
if (timer === 1) {
clearInterval(interval)
}
}, 1000)
}
}, [stage])
and i have a div like below that just shows the counter value
<div>{timer}</div>
in my setInterval, when i use console.log(timer) it always prints out 60. But inside the div, the value starts with 60 and in the next second it will always be 59.
What am i doing wrong here?
console.loging before you-1from the timer, so even if it was synchronous it would print out 60. But assetTimeris asynchronous, you can't rely on the log ever showing the new value immediately, you would need an effect listening for changes totimer.