flushSync
Forces React to flush all pending updates synchronously, ensuring the DOM is immediately updated.Reference
flushSync(callback?)
Call flushSync to force React to flush any pending work and update the DOM synchronously.
/src/shared/ReactDOMFlushSync.js:17-50
Parameters
() => void
Optional callback function containing state updates. React will immediately flush these updates and apply them to the DOM before
flushSync returns.Returns
undefined
Returns nothing. All updates are flushed synchronously before the function returns.
When to Use flushSync
1. Third-Party Integrations
When integrating with third-party libraries that need immediate DOM access:2. Print Functionality
Ensure all updates are applied before printing:3. Focus Management
When you need to focus an element immediately after rendering:4. Measuring Layout
When you need to measure an element immediately after an update:5. Drag and Drop
Ensure immediate updates during drag operations:Performance Impact
How React Normally Works
By default, React batches updates for performance:With flushSync (Slower)
Performance Comparison
Common Pitfalls
1. Using in Event Handlers (Usually Unnecessary)
2. Using in Effects
3. Nesting flushSync Calls
4. Using for Animation
Alternatives to flushSync
1. Use Effects Instead
2. Use Layout Effects
3. Use Refs for Immediate Values
4. Use Callback Refs
TypeScript
Testing
Debugging
Enable logging to see when flushSync is called:Strict Mode Compatibility
flushSync works in Strict Mode but may cause warnings if used in render:
Best Practices
- Use sparingly - Most apps don’t need flushSync
- Measure performance - Profile before and after
- Consider alternatives - Effects, layout effects, refs
- Document usage - Explain why it’s necessary
- Avoid in loops - Extremely slow
- Test without it first - May not be needed
Browser Compatibility
Works in all browsers that support React:- Chrome 90+
- Firefox 88+
- Safari 14.1+
- Edge 90+
Related APIs
- useLayoutEffect - Run effects synchronously after DOM updates
- useEffect - Run effects asynchronously
- startTransition - Mark updates as non-urgent (opposite of flushSync)
- createRoot - Enable concurrent features