Skip to main content

flushSync

Forces React to flush all pending updates synchronously, ensuring the DOM is immediately updated.
flushSync can significantly hurt performance. Use sparingly and only when necessary.

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

  1. Use sparingly - Most apps don’t need flushSync
  2. Measure performance - Profile before and after
  3. Consider alternatives - Effects, layout effects, refs
  4. Document usage - Explain why it’s necessary
  5. Avoid in loops - Extremely slow
  6. 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+