You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: src/content/learn/you-might-not-need-an-effect.md
+1-1Lines changed: 1 addition & 1 deletion
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -408,7 +408,7 @@ function Game() {
408
408
409
409
There are two problems with this code.
410
410
411
-
First problem is that it is very inefficient: the component (and its children) have to re-render between each `set` call in the chain. In the example above, in the worst case (`setCard` → render → `setGoldCardCount` → render → `setRound` → render → `setIsGameOver` → render) there are three unnecessary re-renders of the tree below.
411
+
The first problem is that it is very inefficient: the component (and its children) have to re-render between each `set` call in the chain. In the example above, in the worst case (`setCard` → render → `setGoldCardCount` → render → `setRound` → render → `setIsGameOver` → render) there are three unnecessary re-renders of the tree below.
412
412
413
413
The second problem is that even if it weren't slow, as your code evolves, you will run into cases where the "chain" you wrote doesn't fit the new requirements. Imagine you are adding a way to step through the history of the game moves. You'd do it by updating each state variable to a value from the past. However, setting the `card` state to a value from the past would trigger the Effect chain again and change the data you're showing. Such code is often rigid and fragile.
Copy file name to clipboardExpand all lines: src/content/reference/react/useMemo.md
+76Lines changed: 76 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -1055,6 +1055,82 @@ label {
1055
1055
1056
1056
---
1057
1057
1058
+
### Слишком частые вызовы эффекта {/*preventing-an-effect-from-firing-too-often*/}
1059
+
1060
+
Время от времени вам могут понадобиться значения внутри [эффекта:](/learn/synchronizing-with-effects)
1061
+
1062
+
```js {4-7,10}
1063
+
functionChatRoom({ roomId }) {
1064
+
const [message, setMessage] =useState('');
1065
+
1066
+
constoptions= {
1067
+
serverUrl:'https://localhost:1234',
1068
+
roomId: roomId
1069
+
}
1070
+
1071
+
useEffect(() => {
1072
+
constconnection=createConnection(options);
1073
+
connection.connect();
1074
+
// ...
1075
+
```
1076
+
1077
+
Это создаёт проблему. [Каждое реактивное значение должно быть объявлено как зависимость вашего эффекта.](/learn/lifecycle-of-reactive-effects#react-verifies-that-you-specified-every-reactive-value-as-a-dependency) Но если вы добавите `options` как зависимость, ваш эффект начнёт постоянно переподключаться к чату:
1078
+
1079
+
1080
+
```js {5}
1081
+
useEffect(() => {
1082
+
constconnection=createConnection(options);
1083
+
connection.connect();
1084
+
return () =>connection.disconnect();
1085
+
}, [options]); // 🔴 Проблема: эта зависимость меняется при каждом рендере
1086
+
// ...
1087
+
```
1088
+
1089
+
Решение – обернуть необходимый в эффекте объект в `useMemo`:
1090
+
1091
+
```js {4-9,16}
1092
+
functionChatRoom({ roomId }) {
1093
+
const [message, setMessage] =useState('');
1094
+
1095
+
constoptions=useMemo(() => {
1096
+
return {
1097
+
serverUrl:'https://localhost:1234',
1098
+
roomId: roomId
1099
+
};
1100
+
}, [roomId]); // ✅ Меняется только тогда, когда меняется roomId
1101
+
1102
+
useEffect(() => {
1103
+
constconnection=createConnection(options);
1104
+
connection.connect();
1105
+
return () =>connection.disconnect();
1106
+
}, [options]); // ✅ Вызывается только тогда, когда меняется options
1107
+
// ...
1108
+
```
1109
+
1110
+
Это гарантирует, что объект `options` один и тот же между повторными рендерами, если `useMemo` возвращает закешированный объект.
1111
+
1112
+
Однако `useMemo` является оптимизацией производительности, а не семантической гарантией. React может отбросить закешированное значение, если [возникнет условие для этого](#caveats). Это также спровоцирует перезапуск эффекта, **так что ещё лучше будет избавиться от зависимости,** переместив ваш объект *внутрь* эффекта:
1113
+
1114
+
```js {5-8,13}
1115
+
functionChatRoom({ roomId }) {
1116
+
const [message, setMessage] =useState('');
1117
+
1118
+
useEffect(() => {
1119
+
constoptions= { // ✅ Нет необходимости для useMemo или зависимостей объекта!
1120
+
serverUrl:'https://localhost:1234',
1121
+
roomId: roomId
1122
+
}
1123
+
1124
+
constconnection=createConnection(options);
1125
+
connection.connect();
1126
+
return () =>connection.disconnect();
1127
+
}, [roomId]); // ✅ Меняется только тогда, когда меняется roomId
1128
+
// ...
1129
+
```
1130
+
1131
+
Теперь ваш код стал проще и не требует `useMemo`. [Узнайте больше об удалении зависимостей эффекта.](/learn/removing-effect-dependencies#move-dynamic-objects-and-functions-inside-your-effect)
1132
+
1133
+
1058
1134
### Мемоизация зависимостей других хуков {/*memoizing-a-dependency-of-another-hook*/}
1059
1135
1060
1136
Предположим, что у нас есть вычисления, зависящие от объекта, создаваемого внутри компонента:
Copy file name to clipboardExpand all lines: src/content/reference/react/useReducer.md
+1Lines changed: 1 addition & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -52,6 +52,7 @@ function MyComponent() {
52
52
#### Замечания {/*caveats*/}
53
53
54
54
* `useReducer -- это хук, поэтому вызывайте его только **на верхнем уровне компонента** или собственных хуков. useReducer нельзя вызвать внутри циклов или условий. Если это нужно, создайте новый компонент и переместите состояние в него.
55
+
* Функция `dispatch` стабильна между повторными рендерами, поэтому вы увидите, что её часто пропускают в списке зависимостей эффекта, но и её включение не вызовет перезапуск эффекта. Если линтер позволяет вам пропускать зависимости без ошибок, то вы можете делать это без опаски. [Узнайте больше об удалении зависимостей эффекта.](/learn/removing-effect-dependencies#move-dynamic-objects-and-functions-inside-your-effect)
55
56
* В строгом режиме React будет **вызывать редюсер и инициализатор дважды**, [чтобы помочь обнаружить случайные побочные эффекты.](#my-reducer-or-initializer-function-runs-twice) Такое поведение проявляется только в режиме разработки и не влияет на продакшен-режим. Логика обновления состояния не изменится, если редюсер и инициализатор – чистые функции (какими они и должны быть). Результат второго вызова проигнорируется.
Copy file name to clipboardExpand all lines: src/content/reference/react/useState.md
+2Lines changed: 2 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -85,6 +85,8 @@ function handleClick() {
85
85
86
86
* React [batches state updates.](/learn/queueing-a-series-of-state-updates) It updates the screen **after all the event handlers have run** and have called their `set` functions. This prevents multiple re-renders during a single event. In the rare case that you need to force React to update the screen earlier, for example to access the DOM, you can use [`flushSync`.](/reference/react-dom/flushSync)
87
87
88
+
* The `set` 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)
89
+
88
90
* Calling the `set` function *during rendering* is only allowed from within the currently rendering component. React will discard its output and immediately attempt to render it again with the new state. This pattern is rarely needed, but you can use it to **store information from the previous renders**. [See an example below.](#storing-information-from-previous-renders)
89
91
90
92
* In Strict Mode, React will **call your updater function twice** in order to [help you find accidental impurities.](#my-initializer-or-updater-function-runs-twice) This is development-only behavior and does not affect production. If your updater function is pure (as it should be), this should not affect the behavior. The result from one of the calls will be ignored.
Copy file name to clipboardExpand all lines: src/content/reference/react/useTransition.md
+2Lines changed: 2 additions & 0 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -80,6 +80,8 @@ function TabContainer() {
80
80
81
81
* The function you pass to `startTransition` must be synchronous. React immediately executes this function, marking all state updates that happen while it executes as Transitions. If you try to perform more state updates later (for example, in a timeout), they won't be marked as Transitions.
82
82
83
+
* The `startTransition` 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)
84
+
83
85
* A state update marked as a Transition will be interrupted by other state updates. For example, if you update a chart component inside a Transition, but then start typing into an input while the chart is in the middle of a re-render, React will restart the rendering work on the chart component after handling the input update.
84
86
85
87
* Transition updates can't be used to control text inputs.
0 commit comments