Skip to content

Commit 61ea255

Browse files
committed
docs: add flushSync Troubleshooting section
1 parent d34c6a2 commit 61ea255

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

src/content/reference/react-dom/flushSync.md

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,3 +131,57 @@ Without `flushSync`, the print dialog will display `isPrinting` as "no". This is
131131
Most of the time, `flushSync` can be avoided, so use `flushSync` as a last resort.
132132

133133
</Pitfall>
134+
135+
---
136+
137+
## Troubleshooting {/*troubleshooting*/}
138+
139+
### I'm getting an error: "flushSync was called from inside a lifecycle method" {/*im-getting-an-error-flushsync-was-called-from-inside-a-lifecycle-method*/}
140+
141+
You might get an error that says: `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.`
142+
143+
This happens when you call `flushSync` while React is already rendering, such as inside:
144+
145+
- Class component lifecycle methods (`componentDidMount`, `componentDidUpdate`, etc.)
146+
- `useLayoutEffect` or `useEffect` hooks
147+
- During the render phase of a component
148+
149+
```js {1-2,4-6}
150+
import { useEffect } from 'react';
151+
import { flushSync } from 'react-dom';
152+
153+
function MyComponent() {
154+
useEffect(() => {
155+
// 🚩 Wrong: calling flushSync inside an effect
156+
flushSync(() => {
157+
setSomething(newValue);
158+
});
159+
}, []);
160+
161+
return <div>{/* ... */}</div>;
162+
}
163+
```
164+
165+
To fix this, move the `flushSync` call outside of the rendering cycle:
166+
167+
```js {3-7}
168+
useEffect(() => {
169+
// ✅ Correct: defer flushSync to a microtask
170+
queueMicrotask(() => {
171+
flushSync(() => {
172+
setSomething(newValue);
173+
});
174+
});
175+
}, []);
176+
```
177+
178+
Or move the `flushSync` call to an event handler:
179+
180+
```js {2-6}
181+
function handleClick() {
182+
// ✅ Correct: flushSync in event handlers is safe
183+
flushSync(() => {
184+
setSomething(newValue);
185+
});
186+
}
187+
```

0 commit comments

Comments
 (0)