MediumEvent Loop & Batching💻 Output Question

Multiple state updates — renders before and after

💡

Hint

React 18 introduced automatic batching — all state updates, even in setTimeout/Promise/fetch, are batched into one render. This is a significant performance improvement.

What does this output?

let renders = 0;
const schedule = [];

// Pre-React 18: each setState in async context caused a render
function legacySetState(value) {
  schedule.push(() => renders++);
  return value;
}

// Simulates pre-18: updates outside React events not batched
function asyncHandler() {
  legacySetState(1);
  legacySetState(2);
  legacySetState(3);
  // Each one scheduled independently
  schedule.forEach(fn => fn());
}

asyncHandler();
console.log(renders);  // would be 3 pre-React 18

// React 18: automatic batching
renders = 0;
schedule.length = 0;

function react18Handler() {
  legacySetState(1);
  legacySetState(2);
  legacySetState(3);
  // React 18 batches these into one render
  renders++; // single batched render
}

react18Handler();
console.log(renders);

Correct Output

3
1

Why this output?

Explanation: Pre-React 18: three separate renders. React 18 automatic batching: one render even in async contexts.

Key Insight: React 18 introduced automatic batching — all state updates, even in setTimeout/Promise/fetch, are batched into one render. This is a significant performance improvement.

Practice predicting output live →

66 output questions with instant feedback

💻 Try Output Quiz