Skip to content

Event handler uses stale state from closure

Quick summary

Your onClick or onChange handler reads state that was captured when the handler was created — it does not see the latest state value.

Why this happens

  • The handler is defined inline in JSX and reads state that changes, but the closure captures the render-time value

  • The handler is memoized with useCallback but its dependency array does not include the state it reads

  • A handler stored in a ref or variable captures state from an earlier render and is called later

Minimal example

✗ Broken code
function Counter() {
  const [count, setCount] = useState(0);
  const handleClick = useCallback(() => {
    console.log(count); // stale!
    setCount(count + 1);
  }, []); // count not in deps
  return <button onClick={handleClick}>{count}</button>;
}
✓ Fixed code
function Counter() {
  const [count, setCount] = useState(0);
  const handleClick = useCallback(() => {
    setCount(prev => prev + 1); // functional update
  }, []); // no deps needed
  return <button onClick={handleClick}>{count}</button>;
}

Using a functional update avoids reading the stale count from the closure, so the handler always increments correctly.

How to diagnose

  • Log the state value inside the handler and compare with the current state shown in the UI

  • Check if the handler is recreated on every render or memoized with stale dependencies

  • Use React DevTools to inspect the handler closure and verify which state values it captures

How to fix

  • Use functional state updates: setCount(prev => prev + 1) to avoid reading stale state in the handler

  • Add all state the handler reads to the useCallback dependency array so it is recreated with fresh values

  • Store the latest state in a ref and read ref.current in the handler to always access the current value

How to prevent

  • Prefer functional state updates over reading state directly in event handlers

  • Include all dependencies in useCallback/useEffect arrays and use the exhaustive-deps eslint rule

Related Resources

Related Glossary

Related Lessons

  • Events

    Learn about event handling.

← Back to language