What does flushSync do in React?
Hint
flushSync takes a callback. What does React do with the updates made inside it?
Full Answer
flushSync(callback) from react-dom runs the callback and applies any state updates made inside it synchronously, so the DOM is updated before the next line runs. It opts those updates out of automatic batching.
import { flushSync } from 'react-dom';
function TodoList() {
const [todos, setTodos] = useState([]);
const listRef = useRef(null);
function addTodo(text) {
flushSync(() => {
setTodos(t => [...t, text]);
});
// The new item is already in the DOM here
listRef.current.lastElementChild.scrollIntoView();
}
// ...
}
Common uses: scrolling to or measuring an element that was just added, moving focus to it, or syncing with a non-React library that reads the DOM straight away.
💡 flushSync forces an extra render and can hurt performance. Use it rarely — most "read the DOM after update" needs are better served by
useLayoutEffect.More React Fundamentals Questions
Practice this in a timed sprint
5 free questions, no signup required