Integrate with external imperative code
A browser API or UI library requires the DOM to reflect a React update before the integration call continues.
React 19+ · Function
flushSync forces React to synchronously process updates inside a callback, making the DOM update immediately. Use it sparingly, mainly when integrating with code that needs to read the DOM right away.
flushSync runs the supplied callback immediately and makes React synchronously process updates produced inside it, so the DOM is updated before the call returns. It may also process pending work or Effects, and it should be reserved for integrations that require immediate DOM access.
flushSync(callback)| Name | Type | Description |
|---|---|---|
callback | function | A function that React invokes immediately; updates from it are flushed synchronously, and additional pending work or Effects may also be processed. |
undefined
import { flushSync } from 'react-dom';
import { createRoot } from 'react-dom/client';
import { useState } from 'react';
function App() {
const [message, setMessage] = useState('Ready');
function handleClick() {
flushSync(() => setMessage('Updated'));
console.log(document.querySelector('#message')?.textContent);
}
return <button onClick={handleClick}><span id="message">{message}</span></button>;
}
createRoot(document.getElementById('root')!).render(<App />);This forces the state update to commit before the subsequent DOM read.
A browser API or UI library requires the DOM to reflect a React update before the integration call continues.
Code must measure or inspect an element immediately after changing related React state.
It is imported from react-dom and accepts a callback. React calls that callback immediately, then synchronously flushes updates caused by it, making the DOM current when the function returns.
Follow-up: What else might be flushed? Pending updates and Effects, including updates scheduled inside Effects, can also be processed.
Use it when code must observe the DOM immediately after a React update, especially while integrating with a browser API or UI library. It is not a general replacement for React's normal scheduling.
Follow-up: Why avoid it? Synchronous work can reduce performance and may expose Suspense fallbacks if an update suspends.
The function returns undefined. Its callback is the only parameter, and React invokes that callback before synchronously processing the updates it contains.
Follow-up: Can it be called during rendering? The documentation warns against render-time use; move the call to an event handler instead.
useStateuseEffectuseLayoutEffectSuspense