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
- Use the new value now: compute it first,
const next = count + 1; setCount(next); save(next);. - Multiple updates based on the previous value:
setCount((c) => c + 1)repeated works;setCount(count + 1)repeated does not. - 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
useEffectwith the state as a dependency. - Read the updated DOM (scroll to a new item):
flushSync(() => setItems(...))then read the DOM. - Async code reading state later: functional updates, or refs for the latest value; React 19.2's
useEffectEventfor 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
1import { useState } from "react";2import { flushSync } from "react-dom";34export function Quantity({ onSave }: { onSave: (qty: number) => Promise<void> }) {5 const [qty, setQty] = useState(1);6 const [items, setItems] = useState<string[]>([]);78 async function addOne() {9 const next = qty + 1; // compute the new value once10 setQty(next); // schedules a re-render11 console.log(qty); // still the old value (snapshot)12 await onSave(next); // use `next`, not `qty`13 }1415 function addThree() {16 setQty((q) => q + 1); // updater functions chain correctly17 setQty((q) => q + 1);18 setQty((q) => q + 1);19 }2021 function addItemAndScroll() {22 flushSync(() => setItems((i) => [...i, `Item ${i.length + 1}`])); // DOM updated synchronously23 document.querySelector("#items li:last-child")?.scrollIntoView({ behavior: "smooth" });24 }2526 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.