You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/content/reference/react-dom/flushSync.md
+15-7Lines changed: 15 additions & 7 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -149,13 +149,13 @@ Warning: flushSync was called from inside a lifecycle method. React cannot flush
149
149
150
150
This includes calling `flushSync` inside:
151
151
152
-
-During the render phase of a component.
152
+
-rendering a component.
153
153
-`useLayoutEffect` or `useEffect` hooks.
154
154
- Class component lifecycle methods.
155
155
156
-
For example, calling `flushSync` in an Effect will noop and warn:
156
+
For example, calling `flushSync` in an Effect will noop and warn:
157
157
158
-
```js {1-2,4-6}
158
+
```js
159
159
import { useEffect } from'react';
160
160
import { flushSync } from'react-dom';
161
161
@@ -173,18 +173,19 @@ function MyComponent() {
173
173
174
174
To fix this, you usually want to move the `flushSync` call to an event:
175
175
176
-
```js {2-6}
176
+
```js
177
177
functionhandleClick() {
178
178
// ✅ Correct: flushSync in event handlers is safe
179
179
flushSync(() => {
180
180
setSomething(newValue);
181
181
});
182
182
}
183
+
```
183
184
184
185
185
-
If it's difficult to move to an event, you can move the flush outside render using a microtask:
186
+
If it's difficult to move to an event, you can defer `flushSync` in a microtask:
186
187
187
-
```js {3-7}
188
+
```js {3,7}
188
189
useEffect(() => {
189
190
// ✅ Correct: defer flushSync to a microtask
190
191
queueMicrotask(() => {
@@ -193,5 +194,12 @@ useEffect(() => {
193
194
});
194
195
});
195
196
}, []);
196
-
197
197
```
198
+
199
+
This will allow the current render to finish and schedule another syncronous render to flush the updates.
200
+
201
+
<Pitfall>
202
+
203
+
`flushSync` can significantly hurt performance, but this particular pattern is even worse for performance. Exhaust all other options before calling `flushSync` in a microtask as an escape hatch.
0 commit comments