The flushSync function forces React to flush pending updates synchronously. Here's when and how to use it.
Basic Usage#
Scroll Position Management#
DOM Measurements#
Animation Coordination#
Focus Management#
Third-Party Library Integration#
Form Validation#
Modal Close with Cleanup#
Batching Override#
Best Practices#
When to Use:
✓ DOM measurements after update
✓ Scroll position management
✓ Focus after render
✓ Third-party library sync
Performance:
✗ Avoid in hot paths
✗ Don't use for every update
✗ Prefer React's batching
✗ Consider alternatives first
Alternatives:
✓ useLayoutEffect for measurements
✓ useEffect for most side effects
✓ ref callbacks for elements
✓ State lifting for coordination
Avoid:
✗ Inside render functions
✗ For animation frames
✗ In tight loops
✗ When batching works
Conclusion#
The flushSync function forces synchronous DOM updates when you need immediate access to updated DOM. Use it sparingly for focus management, scroll positioning, and third-party library integration. In most cases, React's automatic batching and useLayoutEffect provide better alternatives with less performance impact.