Automatic batching in timers and promises
Before React 18 (with the old ReactDOM.render), the three updates after await would have caused three renders. With createRoot they are batched into one.
React collects all the state updates from one event into a queue and renders once at the end (batching); pass an updater function like setN(n => n + 1) when the next value depends on the previous one, so each update builds on the latest queued value.
Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.
Ready for more? This phase has 5 hands-on exercises with automatic checks.
Practice questions
Write the code in the editor, run it, then open the model answer to compare.
A Likes component has a +10 button that should call a helper addOne() ten times in a loop. Write addOne so the final count really goes up by 10.
Starting from n = 3, what does setN((x) => x * 2); setN(n + 1); setN((x) => x - 1); produce? Show the queue.
Explain it without notes
What is batching, and what changed in React 18?
Why does calling setN(n + 1) three times add only 1?
How does an updater function work, and what does it receive?
With n = 0, what is the result of setN(n + 5); setN((x) => x + 1); setN(42); and why?
Preview
Console
Nothing logged yet.Expected console output
render: guest | idle | 0
render: Asha | saved | 1