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
### Устранение лишних зависимостей от объектов {/*removing-unnecessary-object-dependencies*/}
1479
1479
1480
-
If your Effect depends on an object or a function created during rendering, it might run too often. For example, this Effect re-connects after every render because the `options` object is [different for every render:](/learn/removing-effect-dependencies#does-some-reactive-value-change-unintentionally)
1480
+
Если ваш эффект зависит от объекта или функции, которые создаются во время рендеринга, то возможно **ваш эффект срабатывает слишком часто**. Например, вот этот эффект делает переподключение на каждый рендеринг, т.к. объект `options`[каждый раз новый:](/learn/removing-effect-dependencies#does-some-reactive-value-change-unintentionally)
1481
1481
1482
1482
```js {6-9,12,15}
1483
1483
const serverUrl = 'https://localhost:1234';
1484
1484
1485
1485
function ChatRoom({ roomId }) {
1486
1486
const [message, setMessage] = useState('');
1487
1487
1488
-
constoptions= { // 🚩 This object is created from scratch on every re-render
1488
+
const options = { // 🚩 Этот объект пересоздаётся при каждом рендеринге
1489
1489
serverUrl: serverUrl,
1490
1490
roomId: roomId
1491
1491
};
1492
1492
1493
1493
useEffect(() => {
1494
-
constconnection=createConnection(options); //It's used inside the Effect
1494
+
const connection = createConnection(options); // И используется в эффекте
1495
1495
connection.connect();
1496
1496
return () => connection.disconnect();
1497
-
}, [options]); // 🚩 As a result, these dependencies are always different on a re-render
1497
+
}, [options]); // 🚩 В результате при каждом рендеринге изменяются зависимости
1498
1498
// ...
1499
1499
```
1500
1500
1501
-
Avoid using an object created during rendering as a dependency. Instead, create the object inside the Effect:
1501
+
Постарайтесь не делать созданный во время рендеринга объект зависимостью. Лучше создавайте нужный объект внутри эффекта:
1502
1502
1503
1503
<Sandpack>
1504
1504
@@ -1523,7 +1523,7 @@ function ChatRoom({ roomId }) {
Now that you create the `options`object inside the Effect, the Effect itself only depends on the `roomId` string.
1575
+
Т.к. теперь объект `options`создаётся внутри эффекта, то сам эффект теперь зависит только от строки `roomId`.
1576
1576
1577
-
With this fix, typing into the input doesn't reconnect the chat. Unlike an object which gets re-created, a string like `roomId`doesn't change unless you set it to another value. [Read more about removing dependencies.](/learn/removing-effect-dependencies)
1577
+
Благодаря этой правке, больше не происходит переподключение к чату, когда пользователь печатает в поле ввода. В отличие от пересоздаваемых объектов, строки вроде `roomId`не будут считаться изменившимися, пока не изменятся по значению. [Подробнее об устранении зависимостей.](/learn/removing-effect-dependencies)
1578
1578
1579
1579
---
1580
1580
1581
-
### Removing unnecessary function dependencies {/*removing-unnecessary-function-dependencies*/}
1581
+
### Устранение лишних зависимостей от функций {/*removing-unnecessary-function-dependencies*/}
1582
1582
1583
-
If your Effect depends on an object or a function created during rendering, it might run too often. For example, this Effect re-connects after every render because the `createOptions`function is [different for every render:](/learn/removing-effect-dependencies#does-some-reactive-value-change-unintentionally)
1583
+
Если ваш эффект зависит от объекта или функции, которые создаются во время рендеринга, то возможно **ваш эффект срабатывает слишком часто**. Например, вот этот эффект делает переподключение на каждый рендеринг, т.к. функция `createOptions`[каждый раз новая:](/learn/removing-effect-dependencies#does-some-reactive-value-change-unintentionally)
1584
1584
1585
1585
```js {4-9,12,16}
1586
1586
function ChatRoom({ roomId }) {
1587
1587
const [message, setMessage] = useState('');
1588
1588
1589
-
functioncreateOptions() { // 🚩 This function is created from scratch on every re-render
1589
+
function createOptions() { // 🚩 Эта функция пересоздаётся при каждом рендеринге
1590
1590
return {
1591
1591
serverUrl: serverUrl,
1592
1592
roomId: roomId
1593
1593
};
1594
1594
}
1595
1595
1596
1596
useEffect(() => {
1597
-
constoptions=createOptions(); //It's used inside the Effect
1597
+
const options = createOptions(); // И используется в эффекте
1598
1598
const connection = createConnection();
1599
1599
connection.connect();
1600
1600
return () => connection.disconnect();
1601
-
}, [createOptions]); // 🚩 As a result, these dependencies are always different on a re-render
1601
+
}, [createOptions]); // 🚩 В результате при каждом рендеринге изменяются зависимости
1602
1602
// ...
1603
1603
```
1604
1604
1605
-
By itself, creating a function from scratch on every re-render is not a problem. You don't need to optimize that. However, if you use it as a dependency of your Effect, it will cause your Effect to re-run after every re-render.
1605
+
В самом по себе создании функции при каждом рендеринге нет ничего плохого -- это не требует оптимизации. Однако если такая функция будет зависимостью эффекта, то эффект будет срабатывать при каждом рендеринге.
1606
1606
1607
-
Avoid using a function created during rendering as a dependency. Instead, declare it inside the Effect:
1607
+
Постарайтесь не делать созданную во время рендеринга функцию зависимостью. Лучше объявите нужную функцию внутри эффекта:
1608
1608
1609
1609
<Sandpack>
1610
1610
@@ -1633,7 +1633,7 @@ function ChatRoom({ roomId }) {
Now that you define the `createOptions`function inside the Effect, the Effect itself only depends on the `roomId` string. With this fix, typing into the input doesn't reconnect the chat. Unlike a function which gets re-created, a string like `roomId`doesn't change unless you set it to another value. [Read more about removing dependencies.](/learn/removing-effect-dependencies)
1685
+
Т.к. теперь функция `createOptions`определена внутри эффекта, то сам эффект теперь зависит только от строки `roomId`. Благодаря этой правке, больше не происходит переподключение к чату, когда пользователь печатает в поле ввода. В отличие от пересоздаваемых функций, строки вроде `roomId`не будут считаться изменившимися, пока не изменятся по значению. [Подробнее об устранении зависимостей.](/learn/removing-effect-dependencies)
0 commit comments