Skip to the page

State: snapshots, updates and where state lives · core

setState: snapshots, the update queue and batching

State is a snapshot for each render: setCount does not change count now, it queues an update; React batches all updates from one event and processes the queue in order in the next render.

The notes

What you must know

  • Inside one render, count is a constant. setCount(count + 1) three times queues "set to 1" three times, so one click gives 1, and console.log(count) right after still prints the old value.
  • The updater form setCount(c => c + 1) queues a function; React runs queued functions in order, each getting the previous result, so three calls give +3.
  • Mixed queue: setN(n + 5); setN(n => n + 1); setN(42) ends at 42; replacement values ignore earlier updates.
  • Since React 18 with createRoot, batching is automatic everywhere: event handlers, setTimeout, promises and native listeners. Separate clicks are not batched together.
  • If the new value is the same by Object.is, React can skip re-rendering that component (bail out).
  • flushSync(() => setX(...)) forces a synchronous update, for example to measure the DOM right after it changes. Use it rarely; it hurts performance.
  • Each update gets a lane (priority); React then schedules a render, reconciles and commits.

The red pen

Common traps: mistake → fix

  • Mistake: "Three setCount(count + 1) calls give 3"

    Fix: they give 1; use the updater form.

  • Mistake: "setState is async" (as the whole answer)

    Fix: the precise answer: state is a per-render snapshot and updates are queued and batched.

  • Mistake: "Updates inside setTimeout are not batched"

    Fix: that was React 17 and older (or the legacy ReactDOM.render, removed in React 19).

Easy to hard

Questions interviewers ask, easy to hard

  1. After one click, what does this render and what does it log? (three setCount(count + 1) then console.log(count))
  2. Fix it so the count goes up by 3.
  3. What changed in React 18 for updates inside setTimeout and promises?
  4. When would you use flushSync?
  5. Walk me through exactly what happens after setState is called.

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview