medium10 pts · first answer countsreact-hooksclosures
Stale value in useEffect
This component should log the latest count every second, but it always logs 0. What is the best fix?
function Counter() {
const [count, setCount] = useState(0)
useEffect(() => {
const id = setInterval(() => console.log(count), 1000)
return () => clearInterval(id)
}, [])
return <button onClick={() => setCount(c => c + 1)}>{count}</button>
}Discussion 0
Join free to post in the discussion.
Related questions
- Closures in a var loopFrontend Developer
- Ref value not shown on screenFrontend Developer
- Resize handler that runs many timesFrontend Developer
- Syncing derived values with an effectFrontend Developer
- Race condition in data fetchingFrontend Developer
- Effect that fetches foreverFrontend Developer
- Tooltip flashes in the wrong placeFrontend Developer
- Timer counter stuck at oneMobile App Developer