Beginner LevelReact JS & React 19
When should you use flushSync to force immediate DOM updates?
❓ Interview Prompt: Explain `flushSync` from `react-dom`, opting out of automatic batching, forcing immediate DOM recalculations, and DOM measurement use cases.
'flushSync' (from 'react-dom') forces React to flush any pending state updates synchronously and update the DOM immediately:
Primary Use Case:
Measuring DOM node geometry (e.g. scroll position, element height) immediately after updating state before the browser finishes the current event frame.
Code Implementation Example
jsx
import { useState, useRef } from 'react';
import { flushSync } from 'react-dom';
function ScrollableFeed() {
const [messages, setMessages] = useState([]);
const listRef = useRef();
const addMessage = (newMsg) => {
// Force immediate DOM update so listRef contains new item synchronously!
flushSync(() => {
setMessages(prev => [...prev, newMsg]);
});
// Immediately scroll to bottom of DOM node!
listRef.current.scrollTop = listRef.current.scrollHeight;
};
}💡Forcing immediate DOM updates with flushSync for scroll position measurements.
🎯 Interview Key Takeaway
Use flushSync sparingly when you must synchronously measure DOM geometry immediately after a state update.
#flushSync#react-dom#Batching#Beginner
Back to all React JS & React 19 Questions→