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
37 changes: 18 additions & 19 deletions src/content/reference/react/PureComponent.md
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
---
title: PureComponent
---

<Pitfall>

We recommend defining components as functions instead of classes. [See how to migrate.](#alternatives)
Мы рекомендуем определять компоненты как функции, а не как классы. [См. как выполнить миграцию.](#alternatives)

</Pitfall>

<Intro>

`PureComponent` is similar to [`Component`](/reference/react/Component) but it skips re-renders for same props and state. Class components are still supported by React, but we don't recommend using them in new code.
`PureComponent` похож на [`Component`](/reference/react/Component), но он пропускает повторные рендеры при одинаковых пропсах и состоянии. Классовые компоненты по-прежнему поддерживаются React, но мы не рекомендуем использовать их в новом коде.

```js
class Greeting extends PureComponent {
Expand All @@ -26,11 +25,11 @@ class Greeting extends PureComponent {

---

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

### `PureComponent` {/*purecomponent*/}

To skip re-rendering a class component for same props and state, extend `PureComponent` instead of [`Component`:](/reference/react/Component)
Чтобы пропустить повторный рендер классового компонента при одинаковых пропсах и состоянии, наследуйте `PureComponent` вместо [`Component`:](/reference/react/Component)

```js
import { PureComponent } from 'react';
Expand All @@ -42,18 +41,18 @@ class Greeting extends PureComponent {
}
```

`PureComponent` is a subclass of `Component` and supports [all the `Component` APIs.](/reference/react/Component#reference) Extending `PureComponent` is equivalent to defining a custom [`shouldComponentUpdate`](/reference/react/Component#shouldcomponentupdate) method that shallowly compares props and state.
`PureComponent` является подклассом `Component` и поддерживает [все API `Component`.](/reference/react/Component#reference) Наследование `PureComponent` эквивалентно определению пользовательского метода [`shouldComponentUpdate`](/reference/react/Component#shouldcomponentupdate), который выполняет поверхностное сравнение пропсов и состояния.


[See more examples below.](#usage)
[См. больше примеров ниже.](#usage)

---

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

### Skipping unnecessary re-renders for class components {/*skipping-unnecessary-re-renders-for-class-components*/}
### Пропуск ненужных повторных рендеров для классовых компонентов {/*skipping-unnecessary-re-renders-for-class-components*/}

React normally re-renders a component whenever its parent re-renders. As an optimization, you can create a component that React will not re-render when its parent re-renders so long as its new props and state are the same as the old props and state. [Class components](/reference/react/Component) can opt into this behavior by extending `PureComponent`:
React обычно повторно рендерит компонент всякий раз, когда рендерится его родитель. В качестве оптимизации вы можете создать компонент, который React не будет повторно рендерить, когда рендерится его родитель, при условии, что его новые пропсы и состояние совпадают со старыми пропсами и состоянием. [Классовые компоненты](/reference/react/Component) могут использовать это поведение, наследуя `PureComponent`:

```js {1}
class Greeting extends PureComponent {
Expand All @@ -63,9 +62,9 @@ class Greeting extends PureComponent {
}
```

A React component should always have [pure rendering logic.](/learn/keeping-components-pure) This means that it must return the same output if its props, state, and context haven't changed. By using `PureComponent`, you are telling React that your component complies with this requirement, so React doesn't need to re-render as long as its props and state haven't changed. However, your component will still re-render if a context that it's using changes.
React-компонент всегда должен иметь [чистую логику рендеринга.](/learn/keeping-components-pure) Это означает, что он должен возвращать одинаковый результат, если его пропсы, состояние и контекст не изменились. Используя `PureComponent`, вы сообщаете React, что ваш компонент соответствует этому требованию, поэтому React не нужно повторно рендерить его, пока его пропсы и состояние не изменятся. Однако ваш компонент всё равно будет повторно рендериться, если изменится контекст, который он использует.

In this example, notice that the `Greeting` component re-renders whenever `name` is changed (because that's one of its props), but not when `address` is changed (because it's not passed to `Greeting` as a prop):
В этом примере обратите внимание, что компонент `Greeting` повторно рендерится при каждом изменении `name` (поскольку это один из его пропсов), но не при изменении `address` (поскольку он не передаётся в `Greeting` как пропс):

<Sandpack>

Expand Down Expand Up @@ -109,17 +108,17 @@ label {

<Pitfall>

We recommend defining components as functions instead of classes. [See how to migrate.](#alternatives)
Мы рекомендуем определять компоненты как функции, а не как классы. [См. как выполнить миграцию.](#alternatives)

</Pitfall>

---

## Alternatives {/*alternatives*/}
## Альтернативы {/*alternatives*/}

### Migrating from a `PureComponent` class component to a function {/*migrating-from-a-purecomponent-class-component-to-a-function*/}
### Миграция классового компонента `PureComponent` на функцию {/*migrating-from-a-purecomponent-class-component-to-a-function*/}

We recommend using function components instead of [class components](/reference/react/Component) in new code. If you have some existing class components using `PureComponent`, here is how you can convert them. This is the original code:
Мы рекомендуем использовать функциональные компоненты вместо [классовых компонентов](/reference/react/Component) в новом коде. Если у вас есть существующие классовые компоненты, использующие `PureComponent`, вот как вы можете их преобразовать. Это исходный код:

<Sandpack>

Expand Down Expand Up @@ -161,7 +160,7 @@ label {

</Sandpack>

When you [convert this component from a class to a function,](/reference/react/Component#alternatives) wrap it in [`memo`:](/reference/react/memo)
Когда вы [преобразуете этот компонент из класса в функцию,](/reference/react/Component#alternatives) оберните его в [`memo`:](/reference/react/memo)

<Sandpack>

Expand Down Expand Up @@ -203,6 +202,6 @@ label {

<Note>

Unlike `PureComponent`, [`memo`](/reference/react/memo) does not compare the new and the old state. In function components, calling the [`set` function](/reference/react/useState#setstate) with the same state [already prevents re-renders by default,](/reference/react/memo#updating-a-memoized-component-using-state) even without `memo`.
В отличие от `PureComponent`, [`memo`](/reference/react/memo) не сравнивает новое и старое состояние. В функциональных компонентах вызов [`set` функции](/reference/react/useState#setstate) с тем же состоянием [уже предотвращает повторные рендеры по умолчанию,](/reference/react/memo#updating-a-memoized-component-using-state) даже без `memo`.

</Note>
</Note>
Loading