Command Palette

Search for a command to run...

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

setN(n + 1) three times versus the updater three times

Each click causes exactly one render (batching), even with three setter calls. Values add 1; updaters add 3.

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?

setN(n + 1) three times versus the updater three times

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

render: plain = 0 | updater = 0
render: plain = 1 | updater = 0
render: plain = 1 | updater = 3