React Reference ยท react-dom Client APIs
React flushSync() function
Reference for flushSync from react-dom: force React to apply state updates to the DOM immediately, when it is needed, and why it should be a last resort.
flushSync(callback) runs a callback and then makes React apply every state update scheduled inside it to the DOM before flushSync returns. Normally React batches updates and commits them a moment later, so code that reads the DOM right after setState sees the old content.
You need it in a few narrow cases: reading layout right after an update (scrolling to a newly added list item, measuring a node), or integrating with browser APIs that require the DOM to be ready in the same tick, such as some view-transition and print flows.
import { flushSync } from 'react-dom'; flushSync(() => { setTodos([...todos, newTodo]); }); // the new <li> is in the DOM here
Try it
Syntax
flushSync(callback)
| Parameter | Description |
|---|---|
callback |
A function that triggers state updates (setState, dispatch). Updates made inside are flushed together. |
Returns undefined.
Errors and edge cases
- Calling
flushSyncwhile React is rendering (inside a component body or during an effect phase) logs a warning and does nothing, because React cannot interrupt its own render. - Updates scheduled before the call, such as pending transitions, are not necessarily forced; only work caused inside the callback is guaranteed to flush.
Usage notes
- It is an escape hatch and hurts performance: it forces a synchronous render and commit, bypassing batching. Prefer
useEffect/useLayoutEffectto react to state changes, since both run after the DOM updates. - For scrolling to new content, a
useLayoutEffector a ref callback that runs when the item mounts is usually cleaner thanflushSync. - It may force pending
Suspensefallbacks to show immediately instead of keeping old UI, so avoid it around data-driven updates. - Server-side it is not meaningful. Import it from
react-dom, notreact-dom/client. - Wrap only the update that must be visible; keep the callback tiny.
- In tests,
act()is the tool to flush updates; do not sprinkleflushSyncin test code.