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: 27 additions & 29 deletions src/content/reference/react/Profiler.md
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
---
title: <Profiler>
---

<Intro>

`<Profiler>` lets you measure rendering performance of a React tree programmatically.
`<Profiler>` позволяет программно измерять производительность рендеринга дерева React.

```js
<Profiler id="App" onRender={onRender}>
Expand All @@ -18,11 +17,11 @@ title: <Profiler>

---

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

### `<Profiler>` {/*profiler*/}

Wrap a component tree in a `<Profiler>` to measure its rendering performance.
Оберните дерево компонентов в `<Profiler>`, чтобы измерить его производительность рендеринга.

```js
<Profiler id="App" onRender={onRender}>
Expand All @@ -32,41 +31,41 @@ Wrap a component tree in a `<Profiler>` to measure its rendering performance.

#### Props {/*props*/}

* `id`: A string identifying the part of the UI you are measuring.
* `onRender`: An [`onRender` callback](#onrender-callback) that React calls every time components within the profiled tree update. It receives information about what was rendered and how much time it took.
* `id`: Строка, идентифицирующая измеряемую часть пользовательского интерфейса.
* `onRender`: [`onRender` callback](#onrender-callback), который React вызывает каждый раз, когда компоненты внутри профилируемого дерева обновляются. Он получает информацию о том, что было отрисовано и сколько времени это заняло.

#### Caveats {/*caveats*/}
#### Ограничения {/*caveats*/}

* Profiling adds some additional overhead, so **it is disabled in the production build by default.** To opt into production profiling, you need to enable a [special production build with profiling enabled.](https://fb.me/react-profiling)
* Профилирование добавляет некоторую дополнительную нагрузку, поэтому **по умолчанию оно отключено в production-сборке.** Чтобы включить профилирование в production-сборке, вам нужно включить [специальную production-сборку с включенным профилированием.](https://fb.me/react-profiling)

---

### `onRender` callback {/*onrender-callback*/}

React will call your `onRender` callback with information about what was rendered.
React вызовет ваш `onRender` callback с информацией о том, что было отрисовано.

```js
function onRender(id, phase, actualDuration, baseDuration, startTime, commitTime) {
// Aggregate or log render timings...
// Агрегируйте или записывайте время рендеринга...
}
```

#### Parameters {/*onrender-parameters*/}
#### Параметры {/*onrender-parameters*/}

* `id`: The string `id` prop of the `<Profiler>` tree that has just committed. This lets you identify which part of the tree was committed if you are using multiple profilers.
* `phase`: `"mount"`, `"update"` or `"nested-update"`. This lets you know whether the tree has just been mounted for the first time or re-rendered due to a change in props, state, or Hooks.
* `actualDuration`: The number of milliseconds spent rendering the `<Profiler>` and its descendants for the current update. This indicates how well the subtree makes use of memoization (e.g. [`memo`](/reference/react/memo) and [`useMemo`](/reference/react/useMemo)). Ideally this value should decrease significantly after the initial mount as many of the descendants will only need to re-render if their specific props change.
* `baseDuration`: The number of milliseconds estimating how much time it would take to re-render the entire `<Profiler>` subtree without any optimizations. It is calculated by summing up the most recent render durations of each component in the tree. This value estimates a worst-case cost of rendering (e.g. the initial mount or a tree with no memoization). Compare `actualDuration` against it to see if memoization is working.
* `startTime`: A numeric timestamp for when React began rendering the current update.
* `commitTime`: A numeric timestamp for when React committed the current update. This value is shared between all profilers in a commit, enabling them to be grouped if desirable.
* `id`: Строковое значение `id` пропса дерева `<Profiler>`, которое только что зафиксировалось. Это позволяет вам определить, какая часть дерева была зафиксирована, если вы используете несколько профилировщиков.
* `phase`: `"mount"`, `"update"` или `"nested-update"`. Это позволяет узнать, было ли дерево смонтировано впервые или перерисовано из-за изменения пропсов, состояния или хуков.
* `actualDuration`: Количество миллисекунд, потраченное на рендеринг `<Profiler>` и его потомков для текущего обновления. Это показывает, насколько эффективно поддерево использует мемоизацию (например, [`memo`](/reference/react/memo) и [`useMemo`](/reference/react/useMemo)). В идеале это значение должно значительно уменьшиться после первоначального монтирования, поскольку многие потомки будут перерисовываться только в том случае, если их конкретные пропсы изменятся.
* `baseDuration`: Количество миллисекунд, оценивающее, сколько времени потребуется для повторного рендеринга всего поддерева `<Profiler>` без каких-либо оптимизаций. Оно рассчитывается путем суммирования последних длительностей рендеринга каждого компонента в дереве. Это значение оценивает наихудшую стоимость рендеринга (например, первоначальное монтирование или дерево без мемоизации). Сравните `actualDuration` с ним, чтобы увидеть, работает ли мемоизация.
* `startTime`: Числовой временной штамп, указывающий, когда React начал рендеринг текущего обновления.
* `commitTime`: Числовой временной штамп, указывающий, когда React зафиксировал текущее обновление. Это значение является общим для всех профилировщиков в фиксации, что позволяет группировать их при необходимости.

---

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

### Measuring rendering performance programmatically {/*measuring-rendering-performance-programmatically*/}
### Программное измерение производительности рендеринга {/*measuring-rendering-performance-programmatically*/}

Wrap the `<Profiler>` component around a React tree to measure its rendering performance.
Оберните компонент `<Profiler>` вокруг дерева React, чтобы измерить его производительность рендеринга.

```js {2,4}
<App>
Expand All @@ -77,25 +76,25 @@ Wrap the `<Profiler>` component around a React tree to measure its rendering per
</App>
```

It requires two props: an `id` (string) and an `onRender` callback (function) which React calls any time a component within the tree "commits" an update.
Он требует два пропса: `id` (строка) и `onRender` callback (функция), который React вызывает всякий раз, когда компонент внутри дерева "фиксирует" обновление.

<Pitfall>

Profiling adds some additional overhead, so **it is disabled in the production build by default.** To opt into production profiling, you need to enable a [special production build with profiling enabled.](https://fb.me/react-profiling)
Профилирование добавляет некоторую дополнительную нагрузку, поэтому **по умолчанию оно отключено в production-сборке.** Чтобы включить профилирование в production-сборке, вам нужно включить [специальную production-сборку с включенным профилированием.](https://fb.me/react-profiling)

</Pitfall>

<Note>

`<Profiler>` lets you gather measurements programmatically. If you're looking for an interactive profiler, try the Profiler tab in [React Developer Tools](/learn/react-developer-tools). It exposes similar functionality as a browser extension.
`<Profiler>` позволяет собирать измерения программно. Если вы ищете интерактивный профилировщик, попробуйте вкладку Profiler в [React Developer Tools](/learn/react-developer-tools). Она предоставляет аналогичную функциональность в виде расширения браузера.

</Note>

---

### Measuring different parts of the application {/*measuring-different-parts-of-the-application*/}
### Измерение различных частей приложения {/*measuring-different-parts-of-the-application*/}

You can use multiple `<Profiler>` components to measure different parts of your application:
Вы можете использовать несколько компонентов `<Profiler>` для измерения различных частей вашего приложения:

```js {5,7}
<App>
Expand All @@ -108,7 +107,7 @@ You can use multiple `<Profiler>` components to measure different parts of your
</App>
```

You can also nest `<Profiler>` components:
Вы также можете вкладывать компоненты `<Profiler>` друг в друга:

```js {5,7,9,12}
<App>
Expand All @@ -126,7 +125,6 @@ You can also nest `<Profiler>` components:
</App>
```

Although `<Profiler>` is a lightweight component, it should be used only when necessary. Each use adds some CPU and memory overhead to an application.

---
Хотя `<Profiler>` является легковесным компонентом, его следует использовать только при необходимости. Каждое его использование добавляет некоторую нагрузку на процессор и память приложения.

---
Loading