ReactEasy

State not updating immediately?

State does not update immediately because calling a setter only schedules a re-render; the variable in the current render is a constant snapshot. You see the new value in the next render. Use the value you computed, use updater functions for sequential updates, react to changes in effects or during render, and use flushSync only if you must read the updated DOM right away.

The classic surprise

setCount(count + 1);
console.log(count); // old value

count is a const captured by this render. React re-renders the component later with the new value.

Fixes depending on what you need

  1. Use the new value now: compute it first, const next = count + 1; setCount(next); save(next);.
  2. Multiple updates based on the previous value: setCount((c) => c + 1) repeated works; setCount(count + 1) repeated does not.
  3. Do something after the state changes: usually do it in the same event handler with the computed value; if it is synchronization with an external system, use useEffect with the state as a dependency.
  4. Read the updated DOM (scroll to a new item): flushSync(() => setItems(...)) then read the DOM.
  5. Async code reading state later: functional updates, or refs for the latest value; React 19.2's useEffectEvent for effect callbacks.

Batching

React 18+ batches all updates in an event into one render, so several setters still produce one re-render with all new values.

Not a bug

This snapshot behavior is what makes rendering predictable and enables concurrent rendering.

Code example

tsx
1import { useState } from "react";
2import { flushSync } from "react-dom";
3
4export function Quantity({ onSave }: { onSave: (qty: number) => Promise<void> }) {
5 const [qty, setQty] = useState(1);
6 const [items, setItems] = useState<string[]>([]);
7
8 async function addOne() {
9 const next = qty + 1; // compute the new value once
10 setQty(next); // schedules a re-render
11 console.log(qty); // still the old value (snapshot)
12 await onSave(next); // use `next`, not `qty`
13 }
14
15 function addThree() {
16 setQty((q) => q + 1); // updater functions chain correctly
17 setQty((q) => q + 1);
18 setQty((q) => q + 1);
19 }
20
21 function addItemAndScroll() {
22 flushSync(() => setItems((i) => [...i, `Item ${i.length + 1}`])); // DOM updated synchronously
23 document.querySelector("#items li:last-child")?.scrollIntoView({ behavior: "smooth" });
24 }
25
26 return (
27 <div>
28 <p>Qty: {qty}</p>
29 <button onClick={addOne}>+1 and save</button>
30 <button onClick={addThree}>+3</button>
31 <button onClick={addItemAndScroll}>Add item</button>
32 <ul id="items">{items.map((i) => <li key={i}>{i}</li>)}</ul>
33 </div>
34 );
35}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app