please how do i fix my react timer, it stays at 1 😭
good evening everyone 🙏🏾 i'm building a pomodoro timer for my portfolio. the seconds go from 0 to 1 and then it just stays at 1 forever. no error in the console. i just came across something called "stale closure" but i don't understand it. here is my code: import { useEffect, useState } from 'react' function Timer() { const [seconds, setSeconds] = useState(0) useEffect(() => { const id = setInterval(() => {…
Accepted answer
ah this one na classic. the interval callback catch "seconds" when it was 0, and because your useEffect get [] e no go run again, so every second e dey do 0 + 1. forever 1 😂 fix am like this: useEffect(() => { const id = setInterval(() => { setSeconds((s) => s + 1) }, 1000) return () => clearInterval(id) }, []) setSeconds((s) => s + 1) means "take whatever the current value is and add 1", so e no care about the old captured value. the clearInterval part is important too. without it, StrictMode go run your effect twice in dev, you go get two intervals, timer go dey count double speed and you go think say na witchcraft