Capítulo 24 de 116

Chapter 24: Queueing a Series of State Updates

Core Idea

React batches state updates within a single event handler (one re-render for all of them, not one per call), and when you need several updates to the same variable to actually compound before the next render, pass an updater function (setN(n => n + 1)) instead of a plain next-value.

Key Concepts

  • Batching: multiple set calls inside one event handler don't each trigger a separate render — React waits until the handler finishes, then re-renders once with all the updates applied. This keeps the UI from doing wasted intermediate renders and avoids a component rendering with only "half" its handler's updates applied.
  • Plain value form doesn't compound: setNumber(number + 1) called three times in a row all read the same fixed number from this render's snapshot (Ch 23) — so they all request the same next value, not three increments.
  • Updater function form compounds: setNumber(n => n + 1) tells React "queue this transformation" instead of "replace with this value." React processes queued updater functions in order during the next render, feeding each one's return value as the n argument to the next — so three queued n => n + 1 calls genuinely produce +3.
  • Mixing replace and update matters: if you call the plain-value form after an updater function (or vice versa) in the same handler, the plain-value call simply overwrites whatever was queued before it — order and form both matter to the final result.
  • Naming convention: updater function parameters are typically the first letter(s) of the state variable (n for number, prevX also common) to keep handlers concise and readable.

Code Examples

<button onClick={() => {
  setNumber(n => n + 1);
  setNumber(n => n + 1);
  setNumber(n => n + 1);
}}>+3</button>
  • What it demonstrates: three queued updater functions correctly compound to +3, unlike the plain-value equivalent from Ch 23 which only reaches +1.

Key Takeaways

  1. Default to the updater-function form (setX(x => ...)) whenever a state update depends on the state's previous value — it's the only form immune to the same-render "stale value" trap.
  2. Batching means "several set calls in one handler = one re-render," which is why relying on an intermediate re-render happening mid-handler is a bug, not a valid strategy.
  3. An updater function only needs to be pure and take the pending state as its argument — it should not itself cause side effects.

Connects To

  • Ch 23 (State as a Snapshot): the exact limitation (fixed values within a render) that updater functions work around.
  • Ch 21 (State: A Component's Memory): the base useState mechanics this chapter builds on.