Skip to content

Concurrent state updates overwrite each other

Quick summary

You called setState with a value computed from the current state — if multiple updates happen before re-render, only the last one applies.

Why this happens

  • You use setCount(count + 1) in multiple places and they fire before re-render, so all read the same stale count

  • An async operation reads state, computes a new value, and calls setState — by then, state may have changed

  • Multiple event handlers or effects update the same state with non-functional updates, causing lost updates

Minimal example

✗ Broken code
function Counter() {
  const [count, setCount] = useState(0);
  const incrementTwice = () => {
    setCount(count + 1); // reads stale count
    setCount(count + 1); // reads same stale count = +1 total
  };
  return <button onClick={incrementTwice}>{count}</button>;
}
✓ Fixed code
function Counter() {
  const [count, setCount] = useState(0);
  const incrementTwice = () => {
    setCount(prev => prev + 1);
    setCount(prev => prev + 1); // +2 total
  };
  return <button onClick={incrementTwice}>{count}</button>;
}

Functional updates receive the latest state as prev, so each update adds 1 to the current value, resulting in +2 total.

How to diagnose

  • Log state reads and writes to detect cases where multiple updates read the same stale value

  • Check if the state update uses the current state value directly (setX(x + 1)) instead of a functional update

  • Test rapid successive updates (e.g., double-clicking) to see if some updates are lost

How to fix

  • Use functional updates: setCount(prev => prev + 1) to ensure each update builds on the latest state

  • Batch related updates into a single state object or use useReducer for complex multi-field updates

  • Use a ref to accumulate changes and flush them in a single state update if updates are very rapid

How to prevent

  • Always use functional updates when the new state depends on the previous state

  • Use useReducer for complex state transitions that involve multiple related fields

Related Resources

Related Glossary

Related Lessons

← Back to language