Course contentsShow
← React
Lesson 744 of 2,39620. useReducerFree lesson

State Transitions That Depend on Previous State

Multiple setState calls can cause stale closure bugs; a reducer guarantees you're working with the correct current state.

State Transitions That Depend on Previous State

What You'll Learn

You'll discover why calling setState multiple times in quick succession can lead to bugs when each call depends on the previous state value.

The Stale Closure Problem

When you call setState multiple times based on the current state value, you might assume each call sees the updated value from the previous call. This is wrong. Each call captures the state value from when the function was created—a "stale closure."

function Counter() {
  const [count, setCount] = useState(0);

  function handleClick() {
    setCount(count + 1);  // Reads count = 0
    setCount(count + 1);  // Also reads count = 0!
    setCount(count + 1);  // Still reads count = 0!
    // Result: count becomes 1, not 3
  }

  return <button onClick={handleClick}>Increment 3x</button>;
}

All three setCount calls read the same count value (0), so the final result is 1, not 3.

The Reducer Guarantee

A reducer function receives the current state as its first argument, guaranteed to be up-to-date. React ensures each action processes against the actual current state, not a stale closure:

function counterReducer(state, action) {
  // 'state' is always the correct current value
  switch (action.type) {
    case 'INCREMENT':
      return state + 1;  // Works correctly
    default:
      return state;
  }
}

Even if you dispatch multiple actions rapidly, each one processes against the correctly updated state from the previous action.

This is why useReducer shines when state transitions depend on previous values—it eliminates the stale closure bug by design.

Key Takeaway: When state updates depend on previous state, multiple setState calls can capture stale values. A reducer guarantees you're always working with the correct current state, eliminating this entire class of bugs.