Skip to content
RED SAGSkills
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>
}
Choose one answer

Discussion 0

Join free to post in the discussion.

Related questions