Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 4.5 — Batching and Updater Functions
React · Example 3 of 3

Quiz: mixing values and updaters

Case A: replace with 0 + 5, then 5 + 1 = 6. Case B starts from 6: replace with 11, then 12, then replace with 42. A plain value wipes out everything queued before it.

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.

01

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.

02

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

01

What is batching, and what changed in React 18?

02

Why does calling setN(n + 1) three times add only 1?

03

How does an updater function work, and what does it receive?

04

With n = 0, what is the result of setN(n + 5); setN((x) => x + 1); setN(42); and why?

Quiz: mixing values and updaters

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

after case A: 6
after case B: 42