Is state update asynchronous?
State updates are not applied immediately: calling a setter schedules a re-render, and the new value is only visible in the next render. React batches multiple updates (automatically everywhere since React 18) into one render. The setter itself is not a Promise, so you cannot await it.
What this means in practice
- After
setCount(count + 1),countstill holds the old value in the current function. Each render sees a fixed snapshot of state. - Several
setXcalls in one event handler, timeout, promise callback or native event produce one re-render (automatic batching, React 18+). Before React 18, only updates inside React event handlers were batched. setCount(count + 1)three times adds 1, not 3, because all three use the same snapshot. UsesetCount((c) => c + 1)to chain.
Reacting to the new value
- Compute it first and use it:
const next = count + 1; setCount(next); save(next);. - Or derive work from state in render, or (for side effects) in
useEffectwith the value as a dependency. - Class components:
this.setState(update, callback)runscallbackafter the update.
Forcing a synchronous update
flushSync(() => setX(v)) from react-dom forces React to apply the update and update the DOM immediately, for example to scroll to a newly added item. Use rarely; it hurts performance.
Concurrent rendering
Updates inside startTransition are lower priority and can be interrupted. In React 19.3, separate transitions also render independently, so one slow transition does not hold up another.
Code example
1import { useState } from "react";2import { flushSync } from "react-dom";34export function SnapshotDemo() {5 const [count, setCount] = useState(0);6 const [items, setItems] = useState<string[]>([]);78 function handleClick() {9 setCount(count + 1);10 console.log(count); // still the OLD value: state is a snapshot for this render11 }1213 function addAndScroll() {14 flushSync(() => setItems((i) => [...i, `Item ${i.length + 1}`]));15 // DOM is already updated here16 document.getElementById("list")?.lastElementChild?.scrollIntoView();17 }1819 return (20 <div>21 <button onClick={handleClick}>Count {count}</button>22 <button onClick={addAndScroll}>Add + scroll</button>23 <ul id="list" style={{ maxHeight: 80, overflow: "auto" }}>24 {items.map((i) => <li key={i}>{i}</li>)}25 </ul>26 </div>27 );28}
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.