When You Actually Need flushSync
You'll learn: The rare real-world situations where breaking React's batching with flushSync is actually necessary.
The Reality Check
While flushSync exists to force synchronous DOM updates, you'll almost never need it. React's batching exists for good reason—performance. However, there are a few legitimate edge cases where you must measure or interact with the DOM immediately after a state change.
Scenario 1: Measuring DOM After State Changes
Imagine you're building a scrollable chat window. When a new message arrives, you want to scroll to the bottom—but only after the new message renders:
import { flushSync } from 'react-dom';
function addMessage(newMessage) {
flushSync(() => {
setMessages(prev => [...prev, newMessage]);
});
// DOM is updated NOW, so we can measure it
scrollContainerRef.current.scrollTop = scrollContainerRef.current.scrollHeight;
}
Without flushSync, the scroll happens before the new message renders, scrolling to the old height.
Scenario 2: Third-Party Library Integration
Some non-React libraries expect the DOM to be in a specific state immediately. For example, a legacy jQuery plugin or a canvas library that needs precise measurements:
function updateChart(data) {
flushSync(() => {
setChartData(data);
});
// Legacy library reads DOM dimensions right away
thirdPartyChart.resize(containerRef.current.offsetWidth);
}
When You Don't Need It
95% of the time, useEffect or useLayoutEffect handle post-render logic better. Only reach for flushSync when synchronous DOM access is absolutely required in the same function scope.
Key Takeaway: Use flushSync only for rare DOM measurement needs or third-party library integrations that require synchronous updates—otherwise stick with React's automatic batching for better performance.