Chapter 103: flushSync
Core Idea
flushSync(callback) forces React to apply any state updates inside callback synchronously, immediately, and commit them to the DOM before flushSync returns — an escape hatch for the rare case where code outside React's control (a third-party library, a browser API callback) needs to read the DOM immediately after a state change, not on React's normal batched schedule.
Key Concepts
- Bypasses batching: normally React batches multiple state updates into one render/commit pass (Ch 24) for efficiency;
flushSync forces the update(s) inside it to skip that batching and commit right away, synchronously.
- Real performance cost: forcing a synchronous flush removes React's ability to optimize/batch, which can noticeably hurt performance if overused — this is explicitly framed as a last-resort tool, not a general pattern.
- Typical use case: integrating with a non-React API that needs the DOM to already reflect a just-triggered state change before it continues — e.g. a browser print dialog, or a third-party DOM library reading layout immediately after triggering a React update.
- Doesn't change what state does, only when it's committed — the actual state transition and re-render logic work exactly the same; only the timing of the DOM commit is forced to be synchronous instead of deferred/batched.
Code Examples
function handleClick() {
flushSync(() => {
setIsPrinting(true);
});
window.print(); // DOM already reflects isPrinting=true by this point
}
- What it demonstrates: forcing the DOM to reflect
isPrinting before calling a browser API that needs the updated layout immediately, rather than trusting React's normal batched timing.
Key Takeaways
- Treat
flushSync as a rare escape hatch for third-party/browser-API integration timing issues, not a default tool for "make my update happen faster."
- It has a real performance cost by design — it removes batching for the wrapped update.
- It changes commit timing, not the update's actual behavior or correctness semantics.
Connects To
- Ch 24 (Queueing a Series of State Updates): the batching behavior this function deliberately bypasses.
- Ch 22 (Render and Commit): the commit step this function forces to happen immediately.