05 · React & Fiber Reconciliation
mediumpredictionjavascript~6 min

Predict Batched State Updates

Objective: Tell value updates apart from functional updates when several are batched.

This mini model queues updates and applies them on flush, like React batching inside one event handler. Predict both log lines.

  • Write one value per line, in print order.
Read the code, then type what it prints
let state = 0;
let pending = [];
const setState = (u) => pending.push(u);
const flush = () => {
  for (const u of pending) state = typeof u === "function" ? u(state) : u;
  pending = [];
};

function onClick() {
  setState(state + 1);
  setState(state + 1);
  setState((s) => s + 1);
  console.log(`during: ${state}`);
}

onClick();
flush();
console.log(`after: ${state}`);
Output
> Nothing has run yet.
Interview follow-up questions
  • Why does `setCount(count + 1)` twice only add one in React?
  • When would you reach for the functional form?
  • How did automatic batching in React 18 change updates outside event handlers?