Skip to content

Commit 15cae40

Browse files
committed
translate notes about effect dependencies
1 parent 40aad1b commit 15cae40

File tree

2 files changed

+14
-24
lines changed

2 files changed

+14
-24
lines changed

src/content/reference/react/useMemo.md

Lines changed: 13 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1055,12 +1055,9 @@ label {
10551055

10561056
---
10571057

1058-
<<<<<<< HEAD
1059-
### Мемоизация зависимостей других хуков {/*memoizing-a-dependency-of-another-hook*/}
1060-
=======
1061-
### Preventing an Effect from firing too often {/*preventing-an-effect-from-firing-too-often*/}
1058+
### Слишком частые вызовы эффекта {/*preventing-an-effect-from-firing-too-often*/}
10621059

1063-
Sometimes, you might want to use a value inside an [Effect:](/learn/synchronizing-with-effects)
1060+
Время от времени вам могут понадобиться значения внутри [эффекта:](/learn/synchronizing-with-effects)
10641061

10651062
```js {4-7,10}
10661063
function ChatRoom({ roomId }) {
@@ -1077,19 +1074,19 @@ function ChatRoom({ roomId }) {
10771074
// ...
10781075
```
10791076
1080-
This creates a problem. [Every reactive value must be declared as a dependency of your Effect.](/learn/lifecycle-of-reactive-effects#react-verifies-that-you-specified-every-reactive-value-as-a-dependency) However, if you declare `options` as a dependency, it will cause your Effect to constantly reconnect to the chat room:
1077+
Это создаёт проблему. [Каждое реактивное значение должно быть объявлено как зависимость вашего эффекта.](/learn/lifecycle-of-reactive-effects#react-verifies-that-you-specified-every-reactive-value-as-a-dependency) Но если вы добавите `options` как зависимость, ваш эффект начнёт постоянно переподключаться к чату:
10811078
10821079
10831080
```js {5}
10841081
useEffect(() => {
10851082
const connection = createConnection(options);
10861083
connection.connect();
10871084
return () => connection.disconnect();
1088-
}, [options]); // 🔴 Problem: This dependency changes on every render
1085+
}, [options]); // 🔴 Проблема: эта зависимость меняется при каждом рендере
10891086
// ...
10901087
```
10911088
1092-
To solve this, you can wrap the object you need to call from an Effect in `useMemo`:
1089+
Решение – обернуть необходимый в эффекте объект в `useMemo`:
10931090
10941091
```js {4-9,16}
10951092
function ChatRoom({ roomId }) {
@@ -1100,43 +1097,41 @@ function ChatRoom({ roomId }) {
11001097
serverUrl: 'https://localhost:1234',
11011098
roomId: roomId
11021099
};
1103-
}, [roomId]); //Only changes when roomId changes
1100+
}, [roomId]); //Меняется только тогда, когда меняется roomId
11041101

11051102
useEffect(() => {
1106-
const options = createOptions();
11071103
const connection = createConnection(options);
11081104
connection.connect();
11091105
return () => connection.disconnect();
1110-
}, [options]); //Only changes when createOptions changes
1106+
}, [options]); //Вызывается только тогда, когда меняется options
11111107
// ...
11121108
```
11131109
1114-
This ensures that the `options` object is the same between re-renders if `useMemo` returns the cached object.
1110+
Это гарантирует, что объект `options` один и тот же между повторными рендерами, если `useMemo` возвращает закешированный объект.
11151111
1116-
However, since `useMemo` is performance optimization, not a semantic guarantee, React may throw away the cached value if [there is a specific reason to do that](#caveats). This will also cause the effect to re-fire, **so it's even better to remove the need for a function dependency** by moving your object *inside* the Effect:
1112+
Однако `useMemo` является оптимизацией производительности, а не семантической гарантией. React может отбросить закешированное значение, если [возникнет условие для этого](#caveats). Это также спровоцирует перезапуск эффекта, **так что ещё лучше будет избавиться от зависимости,** переместив ваш объект *внутрь* эффекта:
11171113
11181114
```js {5-8,13}
11191115
function ChatRoom({ roomId }) {
11201116
const [message, setMessage] = useState('');
11211117

11221118
useEffect(() => {
1123-
const options = { //No need for useMemo or object dependencies!
1119+
const options = { //Нет необходимости для useMemo или зависимостей объекта!
11241120
serverUrl: 'https://localhost:1234',
11251121
roomId: roomId
11261122
}
11271123

11281124
const connection = createConnection(options);
11291125
connection.connect();
11301126
return () => connection.disconnect();
1131-
}, [roomId]); //Only changes when roomId changes
1127+
}, [roomId]); //Меняется только тогда, когда меняется roomId
11321128
// ...
11331129
```
11341130
1135-
Now your code is simpler and doesn't need `useMemo`. [Learn more about removing Effect dependencies.](/learn/removing-effect-dependencies#move-dynamic-objects-and-functions-inside-your-effect)
1131+
Теперь ваш код стал проще и не требует `useMemo`. [Узнайте больше об удалении зависимостей эффекта.](/learn/removing-effect-dependencies#move-dynamic-objects-and-functions-inside-your-effect)
11361132
11371133
1138-
### Memoizing a dependency of another Hook {/*memoizing-a-dependency-of-another-hook*/}
1139-
>>>>>>> c003ac4eb130fca70b88cf3a1b80ce5f76c51ae3
1134+
### Мемоизация зависимостей других хуков {/*memoizing-a-dependency-of-another-hook*/}
11401135
11411136
Предположим, что у нас есть вычисления, зависящие от объекта, создаваемого внутри компонента:
11421137

src/content/reference/react/useReducer.md

Lines changed: 1 addition & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -51,14 +51,9 @@ function MyComponent() {
5151
5252
#### Замечания {/*caveats*/}
5353
54-
<<<<<<< HEAD
5554
* `useReducer -- это хук, поэтому вызывайте его только **на верхнем уровне компонента** или собственных хуков. useReducer нельзя вызвать внутри циклов или условий. Если это нужно, создайте новый компонент и переместите состояние в него.
55+
* Функция `dispatch` стабильна между повторными рендерами, поэтому вы увидите, что её часто пропускают в списке зависимостей эффекта, но и её включение не вызовет перезапуск эффекта. Если линтер позволяет вам пропускать зависимости без ошибок, то вы можете делать это без опаски. [Узнайте больше об удалении зависимостей эффекта.](/learn/removing-effect-dependencies#move-dynamic-objects-and-functions-inside-your-effect)
5656
* В строгом режиме React будет **вызывать редюсер и инициализатор дважды**, [чтобы помочь обнаружить случайные побочные эффекты.](#my-reducer-or-initializer-function-runs-twice) Такое поведение проявляется только в режиме разработки и не влияет на продакшен-режим. Логика обновления состояния не изменится, если редюсер и инициализатор – чистые функции (какими они и должны быть). Результат второго вызова проигнорируется.
57-
=======
58-
* `useReducer` is a Hook, so you can only call it **at the top level of your component** or your own Hooks. You can't call it inside loops or conditions. If you need that, extract a new component and move the state into it.
59-
* The `dispatch` function has a stable identity, so you will often see it omitted from effect dependencies, but including it will not cause the effect to fire. If the linter lets you omit a dependency without errors, it is safe to do. [Learn more about removing Effect dependencies.](/learn/removing-effect-dependencies#move-dynamic-objects-and-functions-inside-your-effect)
60-
* In Strict Mode, React will **call your reducer and initializer twice** in order to [help you find accidental impurities.](#my-reducer-or-initializer-function-runs-twice) This is development-only behavior and does not affect production. If your reducer and initializer are pure (as they should be), this should not affect your logic. The result from one of the calls is ignored.
61-
>>>>>>> c003ac4eb130fca70b88cf3a1b80ce5f76c51ae3
6257

6358
---
6459

0 commit comments

Comments
 (0)