Skip to content
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletions src/content/reference/react-dom/flushSync.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,3 +131,66 @@ Without `flushSync`, the print dialog will display `isPrinting` as "no". This is
Most of the time, `flushSync` can be avoided, so use `flushSync` as a last resort.

</Pitfall>

---

## Troubleshooting {/*troubleshooting*/}

### 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*/}


React cannot `flushSync` in the middle of a render. If you call `flushSync` in render, it will noop and you'll see a warning:

<ConsoleBlock level="error">

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.

</ConsoleBlock level="error">

This can happen when you call `flushSync` inside:

- Class component lifecycle methods (`componentDidMount`, `componentDidUpdate`, etc.)
- `useLayoutEffect` or `useEffect` hooks
- During the render phase of a component

For example, if you call `flushSync` in an Effect:

```js {1-2,4-6}
import { useEffect } from 'react';
import { flushSync } from 'react-dom';

function MyComponent() {
useEffect(() => {
// 🚩 Wrong: calling flushSync inside an effect
flushSync(() => {
setSomething(newValue);
});
}, []);

return <div>{/* ... */}</div>;
}
```

To fix this, move the `flushSync` call outside of the rendering cycle:

```js {3-7}
useEffect(() => {
// ✅ Correct: defer flushSync to a microtask
queueMicrotask(() => {
flushSync(() => {
setSomething(newValue);
});
});
}, []);
```

Or move the `flushSync` call to an event handler:

```js {2-6}
function handleClick() {
// ✅ Correct: flushSync in event handlers is safe
flushSync(() => {
setSomething(newValue);
});
}
```
Loading