logo by @sawaratsuki1004
React
v19.2
تعلم
مرجع
المجتمع
المدونة

هل هذه الصفحة مفيدة؟

في هذه الصفحة

  • Overview
  • Reference
  • flushSync(callback)
  • Usage
  • Flushing updates for third-party integrations
  • Troubleshooting
  • I’m getting an error: “flushSync was called from inside a lifecycle method”

    react@19.2

  • نظرة عامة
  • Hooks
    • useActionState
    • useCallback
    • useContext
    • useDebugValue
    • useDeferredValue
    • useEffect
    • useEffectEvent
    • useId
    • useImperativeHandle
    • useInsertionEffect
    • useLayoutEffect
    • useMemo
    • useOptimistic
    • useReducer
    • useRef
    • useState
    • useSyncExternalStore
    • useTransition
  • المكونات
    • <Fragment> (<>)
    • <Profiler>
    • <StrictMode>
    • <Suspense>
    • <Activity>
    • <ViewTransition> - هذه الميزة متاحة في أحدث إصدار Canary من React
  • APIs
    • act
    • addTransitionType - هذه الميزة متاحة في أحدث إصدار Canary من React
    • cache
    • cacheSignal
    • captureOwnerStack
    • createContext
    • lazy
    • memo
    • startTransition
    • use
    • experimental_taintObjectReference - هذه الميزة متاحة في أحدث إصدار تجريبي من React
    • experimental_taintUniqueValue - هذه الميزة متاحة في أحدث إصدار تجريبي من React
  • react-dom@19.2

  • Hooks
    • useFormStatus
  • المكونات (Components)
    • Common (e.g. <div>)
    • <form>
    • <input>
    • <option>
    • <progress>
    • <select>
    • <textarea>
    • <link>
    • <meta>
    • <script>
    • <style>
    • <title>
  • APIs
    • createPortal
    • flushSync
    • preconnect
    • prefetchDNS
    • preinit
    • preinitModule
    • preload
    • preloadModule
  • Client APIs
    • createRoot
    • hydrateRoot
  • Server APIs
    • renderToPipeableStream
    • renderToReadableStream
    • renderToStaticMarkup
    • renderToString
    • resume
    • resumeToPipeableStream
  • Static APIs
    • prerender
    • prerenderToNodeStream
    • resumeAndPrerender
    • resumeAndPrerenderToNodeStream
  • React Compiler

  • الإعدادات (Configuration)
    • compilationMode
    • gating
    • logger
    • panicThreshold
    • target
  • Directives
    • "use memo"
    • "use no memo"
  • تصريف المكتبات (Compiling Libraries)
  • React DevTools

  • React Performance tracks
  • eslint-plugin-react-hooks

  • Lints
    • exhaustive-deps
    • rules-of-hooks
    • component-hook-factories
    • config
    • error-boundaries
    • gating
    • globals
    • immutability
    • incompatible-library
    • preserve-manual-memoization
    • purity
    • refs
    • set-state-in-effect
    • set-state-in-render
    • static-components
    • unsupported-syntax
    • use-memo
  • قواعد React (Rules of React)

  • نظرة عامة (Overview)
    • Components و Hooks يجب أن تكون Pure
    • React تستدعي Components و Hooks
    • قواعد Hooks
  • React Server Components

  • Server Components
  • Server Functions
  • Directives
    • 'use client'
    • 'use server'
  • Legacy APIs

  • Legacy React APIs
    • Children
    • cloneElement
    • Component
    • createElement
    • createRef
    • forwardRef
    • isValidElement
    • PureComponent
مرجع API
APIs

flushSync

مأزق

Using flushSync is uncommon and can hurt the performance of your app.

flushSync lets you force React to flush any updates inside the provided callback synchronously. This ensures that the DOM is updated immediately.

flushSync(callback)

  • Reference
    • flushSync(callback)
  • Usage
    • Flushing updates for third-party integrations
  • Troubleshooting
    • I’m getting an error: “flushSync was called from inside a lifecycle method”

Reference

flushSync(callback)

Call flushSync to force React to flush any pending work and update the DOM synchronously.

import { flushSync } from 'react-dom'; flushSync(() => { setSomething(123); });

Most of the time, flushSync can be avoided. Use flushSync as last resort.

See more examples below.

Parameters

  • callback: A function. React will immediately call this callback and flush any updates it contains synchronously. It may also flush any pending updates, or Effects, or updates inside of Effects. If an update suspends as a result of this flushSync call, the fallbacks may be re-shown.

Returns

flushSync returns undefined.

Caveats

  • flushSync can significantly hurt performance. Use sparingly.
  • flushSync may force pending Suspense boundaries to show their fallback state.
  • flushSync may run pending Effects and synchronously apply any updates they contain before returning.
  • flushSync may flush updates outside the callback when necessary to flush the updates inside the callback. For example, if there are pending updates from a click, React may flush those before flushing the updates inside the callback.

Usage

Flushing updates for third-party integrations

When integrating with third-party code such as browser APIs or UI libraries, it may be necessary to force React to flush updates. Use flushSync to force React to flush any state updates inside the callback synchronously:

flushSync(() => { setSomething(123); }); // By this line, the DOM is updated.

This ensures that, by the time the next line of code runs, React has already updated the DOM.

Using flushSync is uncommon, and using it often can significantly hurt the performance of your app. If your app only uses React APIs, and does not integrate with third-party libraries, flushSync should be unnecessary.

However, it can be helpful for integrating with third-party code like browser APIs.

Some browser APIs expect results inside of callbacks to be written to the DOM synchronously, by the end of the callback, so the browser can do something with the rendered DOM. In most cases, React handles this for you automatically. But in some cases it may be necessary to force a synchronous update.

For example, the browser onbeforeprint API allows you to change the page immediately before the print dialog opens. This is useful for applying custom print styles that allow the document to display better for printing. In the example below, you use flushSync inside of the onbeforeprint callback to immediately “flush” the React state to the DOM. Then, by the time the print dialog opens, isPrinting displays “yes”:

import { useState, useEffect } from 'react'; import { flushSync } from 'react-dom'; export default function PrintApp() { const [isPrinting, setIsPrinting] = useState(false); useEffect(() => { function handleBeforePrint() { flushSync(() => { setIsPrinting(true); }) } function handleAfterPrint() { setIsPrinting(false); } window.addEventListener('beforeprint', handleBeforePrint); window.addEventListener('afterprint', handleAfterPrint); return () => { window.removeEventListener('beforeprint', handleBeforePrint); window.removeEventListener('afterprint', handleAfterPrint); } }, []); return ( <> <h1>isPrinting: {isPrinting ? 'yes' : 'no'}</h1> <button onClick={() => window.print()}> Print </button> </> ); }

Without flushSync, the print dialog will display isPrinting as “no”. This is because React batches the updates asynchronously and the print dialog is displayed before the state is updated.

مأزق

flushSync can significantly hurt performance, and may unexpectedly force pending Suspense boundaries to show their fallback state.

Most of the time, flushSync can be avoided, so use flushSync as a last resort.


Troubleshooting

I’m getting an error: “flushSync was called from inside a lifecycle method”

React cannot flushSync in the middle of a render. If you do, it will noop and warn:

Console
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 includes calling flushSync inside:

  • rendering a component.
  • useLayoutEffect or useEffect hooks.
  • Class component lifecycle methods.

For example, calling flushSync in an Effect will noop and warn:

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, you usually want to move the flushSync call to an event:

function handleClick() { // ✅ Correct: flushSync in event handlers is safe flushSync(() => { setSomething(newValue); }); }

If it’s difficult to move to an event, you can defer flushSync in a microtask:

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

This will allow the current render to finish and schedule another syncronous render to flush the updates.

مأزق

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.

السابقcreatePortal
التاليpreconnect

Copyright © Meta Platforms, Inc
no uwu plz
uwu?
Logo by@sawaratsuki1004
تعلم React
بداية سريعة
التثبيت
وصف واجهة المستخدم (UI)
إضافة التفاعلية
إدارة State
مخارج الطوارئ
مرجع API
React APIs
React DOM APIs
المجتمع
ميثاق السلوك
تعرف على الفريق
المساهمون في التوثيق
شكر وتقدير
المزيد
المدونة
React Native
الخصوصية
الشروط
flushSync(callback)
import { flushSync } from 'react-dom';

flushSync(() => {
setSomething(123);
});
flushSync(() => {
setSomething(123);
});
// By this line, the DOM is updated.
Fork
import { useState, useEffect } from 'react';
import { flushSync } from 'react-dom';

export default function PrintApp() {
  const [isPrinting, setIsPrinting] = useState(false);

  useEffect(() => {
    function handleBeforePrint() {
      flushSync(() => {
        setIsPrinting(true);
      })
    }

    function handleAfterPrint() {
      setIsPrinting(false);
    }

    window.addEventListener('beforeprint', handleBeforePrint);
    window.addEventListener('afterprint', handleAfterPrint);
    return () => {
      window.removeEventListener('beforeprint', handleBeforePrint);
      window.removeEventListener('afterprint', handleAfterPrint);
    }
  }, []);

  return (
    <>
      <h1>isPrinting: {isPrinting ? 'yes' : 'no'}</h1>
      <button onClick={() => window.print()}>
        Print
      </button>
    </>
  );
}

import { useEffect } from 'react';
import { flushSync } from 'react-dom';

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

return <div>{/* ... */}</div>;
}
function handleClick() {
// ✅ Correct: flushSync in event handlers is safe
flushSync(() => {
setSomething(newValue);
});
}
useEffect(() => {
// ✅ Correct: defer flushSync to a microtask
queueMicrotask(() => {
flushSync(() => {
setSomething(newValue);
});
});
}, []);