Skip to content
Open
Changes from all 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
56 changes: 28 additions & 28 deletions src/content/reference/react-dom/flushSync.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ title: flushSync

<Pitfall>

Using `flushSync` is uncommon and can hurt the performance of your app.
Использование `flushSync` встречается редко и может ухудшить производительность вашего приложения.

</Pitfall>

<Intro>

`flushSync` lets you force React to flush any updates inside the provided callback synchronously. This ensures that the DOM is updated immediately.
`flushSync` позволяет принудительно выполнить все обновления React внутри предоставленного колбэка синхронно. Это гарантирует немедленное обновление DOM.

```js
flushSync(callback)
Expand All @@ -22,11 +22,11 @@ flushSync(callback)

---

## Reference {/*reference*/}
## Справочник {/*reference*/}

### `flushSync(callback)` {/*flushsync*/}

Call `flushSync` to force React to flush any pending work and update the DOM synchronously.
Вызовите `flushSync`, чтобы принудительно выполнить все ожидающие операции React и синхронно обновить DOM.

```js
import { flushSync } from 'react-dom';
Expand All @@ -36,50 +36,50 @@ flushSync(() => {
});
```

Most of the time, `flushSync` can be avoided. Use `flushSync` as last resort.
В большинстве случаев `flushSync` можно избежать. Используйте `flushSync` в крайнем случае.

[See more examples below.](#usage)
[См. примеры ниже.](#usage)

#### Parameters {/*parameters*/}
#### Параметры {/*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.
* `callback`: Функция. React немедленно вызовет этот колбэк и синхронно выполнит все обновления, содержащиеся в нём. Он также может выполнить любые ожидающие обновления, эффекты или обновления внутри эффектов. Если обновление приостанавливается в результате этого вызова `flushSync`, могут снова отобразиться запасные варианты (`fallback`).

#### Returns {/*returns*/}
#### Возвращаемое значение {/*returns*/}

`flushSync` returns `undefined`.
`flushSync` возвращает `undefined`.

#### Caveats {/*caveats*/}
#### Ограничения {/*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.
* `flushSync` может значительно ухудшить производительность. Используйте с осторожностью.
* `flushSync` может принудительно отобразить запасное состояние (`fallback`) для ожидающих границ Suspense.
* `flushSync` может выполнить ожидающие эффекты и синхронно применить любые обновления, содержащиеся в них, перед возвратом.
* `flushSync` может выполнить обновления вне колбэка при необходимости для выполнения обновлений внутри колбэка. Например, если есть ожидающие обновления от клика, React может выполнить их перед выполнением обновлений внутри колбэка.

---

## Usage {/*usage*/}
## Использование {/*usage*/}

### Flushing updates for third-party integrations {/*flushing-updates-for-third-party-integrations*/}
### Принудительное выполнение обновлений для сторонних интеграций {/*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 <CodeStep step={1}>state updates</CodeStep> inside the callback synchronously:
При интеграции со сторонним кодом, таким как API браузера или библиотеки пользовательского интерфейса, может потребоваться принудительно выполнить обновления React. Используйте `flushSync`, чтобы принудительно выполнить все <CodeStep step={1}>обновления состояния</CodeStep> внутри колбэка синхронно:

```js [[1, 2, "setSomething(123)"]]
flushSync(() => {
setSomething(123);
});
// By this line, the DOM is updated.
// К этой строке DOM будет обновлен.
```

This ensures that, by the time the next line of code runs, React has already updated the DOM.
Это гарантирует, что к моменту выполнения следующей строки кода React уже обновит 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.
**Использование `flushSync` встречается редко, и частое его использование может значительно ухудшить производительность вашего приложения.** Если ваше приложение использует только API React и не интегрируется со сторонними библиотеками, `flushSync` не потребуется.

However, it can be helpful for integrating with third-party code like browser APIs.
Однако он может быть полезен для интеграции со сторонним кодом, таким как API браузера.

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.
Некоторые API браузера ожидают, что результаты внутри колбэков будут записаны в DOM синхронно, к концу колбэка, чтобы браузер мог что-то сделать с отрисованным DOM. В большинстве случаев React обрабатывает это автоматически. Но в некоторых случаях может потребоваться принудительное синхронное обновление.

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":
Например, API браузера `onbeforeprint` позволяет изменить страницу непосредственно перед открытием диалогового окна печати. Это полезно для применения пользовательских стилей печати, которые позволяют документу лучше отображаться при печати. В приведенном ниже примере вы используете `flushSync` внутри колбэка `onbeforeprint`, чтобы немедленно "сбросить" состояние React в DOM. Затем, к моменту открытия диалогового окна печати, `isPrinting` отображает "yes":

<Sandpack>

Expand Down Expand Up @@ -122,12 +122,12 @@ export default function PrintApp() {

</Sandpack>

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` диалоговое окно печати отобразит `isPrinting` как "no". Это связано с тем, что React пакетно обрабатывает обновления асинхронно, и диалоговое окно печати отображается до обновления состояния.

<Pitfall>

`flushSync` can significantly hurt performance, and may unexpectedly force pending Suspense boundaries to show their fallback state.
`flushSync` может значительно ухудшить производительность и неожиданно принудительно отобразить запасное состояние для ожидающих границ Suspense.

Most of the time, `flushSync` can be avoided, so use `flushSync` as a last resort.
В большинстве случаев `flushSync` можно избежать, поэтому используйте `flushSync` в качестве последнего средства.

</Pitfall>
</Pitfall>
Loading