tezvyn:

React State Updates: The Queue and the Updater Function

Source: react.devadvanced

React batches state updates from one event, like a waiter taking a full order before heading to the kitchen. This prevents multiple re-renders. The footgun: `setCount(count + 1)` called three times only increments once, as `count` is fixed for that render.

React batches state updates from one event, like a waiter taking a full order before heading to the kitchen, preventing multiple re-renders. This happens automatically in event handlers. The footgun is calling `setCount(count + 1)` repeatedly; since `count` is a fixed snapshot for that render, the value will only increment once. To correctly queue updates on the same state variable, you must pass an updater function like `setCount(c => c + 1)`.

Read the original → react.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.

React State Updates: The Queue and the Updater Function · Tezvyn