-
Notifications
You must be signed in to change notification settings - Fork 7.8k
Description
Summary
The flushSync
docs don’t mention a very common warning users hit when calling it during render or within a lifecycle method/effect:
"Warning: flushSync was called from inside a lifecycle method. React cannot flush when React is already rendering. Consider moving this call to a scheduler task or micro task."
Adding this information will help developers understand why it happens and how to fix it.
Page
https://react.dev/reference/react-dom/flushSync
Details
The current docs for flushSync
explain its purpose but omit an important and common warning:
Warning: flushSync was called from inside a lifecycle method. React cannot flush when React is already rendering. Consider moving this call to a scheduler task or micro task.
This warning occurs when flushSync
is used inside:
- Class lifecycle methods (
componentDidMount
,componentDidUpdate
) useLayoutEffect
/useEffect
- Render-phase code or other ongoing render work
Why this matters:
Developers frequently encounter this warning without knowing why. The docs should:
- Explicitly mention this scenario.
- Recommend safe alternatives.
Proposed addition to docs:
Add a “When not to use flushSync
” section that explains:
- Don’t call
flushSync
while React is rendering. - The above warning will appear if you do.
- Preferred alternatives:
- Defer to a microtask:
queueMicrotask(() => { flushSync(() => setState(...)); });
- Schedule a macrotask:
setTimeout(() => { flushSync(() => setState(...)); }, 0);
- Use
startTransition
for non-urgent updates. - Move logic to an event handler when possible.
- Defer to a microtask:
Also include a “Common pitfalls” list and a link to community explanations, e.g.:
Understanding React’s flushSync
warning and how to handle it