javascript / expert
Snippet
Forcing Synchronous Updates with flushSync
React normally batches state updates for performance. flushSync forces React to flush any pending work and update the DOM immediately, which is useful for integrating with third-party imperative APIs.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import { flushSync } from 'react-dom';function HeavyComponent() {const [count, setCount] = React.useState(0);const handleClick = () => {flushSync(() => {setCount(c => c + 1);});// The DOM is guaranteed to be updated hereconsole.log('DOM has been updated');};return <button onClick={handleClick}>{count}</button>;}
react
Breakdown
1
import { flushSync } from 'react-dom';
Imports the specialized utility from react-dom to bypass the default asynchronous batching.
2
flushSync(() => { setCount(c => c + 1); });
Wraps the state update; React will perform a synchronous re-render before moving to the next line of code.