Skip to content

Commit 2958bcc

Browse files
committed
Translated removing dependencies of useEffect
1 parent 70db7d7 commit 2958bcc

File tree

1 file changed

+26
-26
lines changed

1 file changed

+26
-26
lines changed

src/content/reference/react/useEffect.md

Lines changed: 26 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1475,30 +1475,30 @@ body {
14751475
---
14761476

14771477

1478-
### Removing unnecessary object dependencies {/*removing-unnecessary-object-dependencies*/}
1478+
### Устранение лишних зависимостей от объектов {/*removing-unnecessary-object-dependencies*/}
14791479

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)
14811481

14821482
```js {6-9,12,15}
14831483
const serverUrl = 'https://localhost:1234';
14841484
14851485
function ChatRoom({ roomId }) {
14861486
const [message, setMessage] = useState('');
14871487
1488-
const options = { // 🚩 This object is created from scratch on every re-render
1488+
const options = { // 🚩 Этот объект пересоздаётся при каждом рендеринге
14891489
serverUrl: serverUrl,
14901490
roomId: roomId
14911491
};
14921492
14931493
useEffect(() => {
1494-
const connection = createConnection(options); // It's used inside the Effect
1494+
const connection = createConnection(options); // И используется в эффекте
14951495
connection.connect();
14961496
return () => connection.disconnect();
1497-
}, [options]); // 🚩 As a result, these dependencies are always different on a re-render
1497+
}, [options]); // 🚩 В результате при каждом рендеринге изменяются зависимости
14981498
// ...
14991499
```
15001500

1501-
Avoid using an object created during rendering as a dependency. Instead, create the object inside the Effect:
1501+
Постарайтесь не делать созданный во время рендеринга объект зависимостью. Лучше создавайте нужный объект внутри эффекта:
15021502

15031503
<Sandpack>
15041504

@@ -1523,7 +1523,7 @@ function ChatRoom({ roomId }) {
15231523
15241524
return (
15251525
<>
1526-
<h1>Welcome to the {roomId} room!</h1>
1526+
<h1>Добро пожаловать в {roomId}!</h1>
15271527
<input value={message} onChange={e => setMessage(e.target.value)} />
15281528
</>
15291529
);
@@ -1534,7 +1534,7 @@ export default function App() {
15341534
return (
15351535
<>
15361536
<label>
1537-
Choose the chat room:{' '}
1537+
Выберите чат:{' '}
15381538
<select
15391539
value={roomId}
15401540
onChange={e => setRoomId(e.target.value)}
@@ -1553,13 +1553,13 @@ export default function App() {
15531553

15541554
```js chat.js
15551555
export function createConnection({ serverUrl, roomId }) {
1556-
// A real implementation would actually connect to the server
1556+
// В реальной реализации здесь было бы настоящее подключение к серверу
15571557
return {
15581558
connect() {
1559-
console.log('Connecting to "' + roomId + '" room at ' + serverUrl + '...');
1559+
console.log('✅ Подключение к чату "' + roomId + '" на ' + serverUrl + '...');
15601560
},
15611561
disconnect() {
1562-
console.log('Disconnected from "' + roomId + '" room at ' + serverUrl);
1562+
console.log('❌ Отключение от чата "' + roomId + '" на ' + serverUrl);
15631563
}
15641564
};
15651565
}
@@ -1572,39 +1572,39 @@ button { margin-left: 10px; }
15721572

15731573
</Sandpack>
15741574

1575-
Now that you create the `options` object inside the Effect, the Effect itself only depends on the `roomId` string.
1575+
Т.к. теперь объект `options` создаётся внутри эффекта, то сам эффект теперь зависит только от строки `roomId`.
15761576

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)
15781578

15791579
---
15801580

1581-
### Removing unnecessary function dependencies {/*removing-unnecessary-function-dependencies*/}
1581+
### Устранение лишних зависимостей от функций {/*removing-unnecessary-function-dependencies*/}
15821582

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)
15841584

15851585
```js {4-9,12,16}
15861586
function ChatRoom({ roomId }) {
15871587
const [message, setMessage] = useState('');
15881588
1589-
function createOptions() { // 🚩 This function is created from scratch on every re-render
1589+
function createOptions() { // 🚩 Эта функция пересоздаётся при каждом рендеринге
15901590
return {
15911591
serverUrl: serverUrl,
15921592
roomId: roomId
15931593
};
15941594
}
15951595
15961596
useEffect(() => {
1597-
const options = createOptions(); // It's used inside the Effect
1597+
const options = createOptions(); // И используется в эффекте
15981598
const connection = createConnection();
15991599
connection.connect();
16001600
return () => connection.disconnect();
1601-
}, [createOptions]); // 🚩 As a result, these dependencies are always different on a re-render
1601+
}, [createOptions]); // 🚩 В результате при каждом рендеринге изменяются зависимости
16021602
// ...
16031603
```
16041604

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+
В самом по себе создании функции при каждом рендеринге нет ничего плохого -- это не требует оптимизации. Однако если такая функция будет зависимостью эффекта, то эффект будет срабатывать при каждом рендеринге.
16061606

1607-
Avoid using a function created during rendering as a dependency. Instead, declare it inside the Effect:
1607+
Постарайтесь не делать созданную во время рендеринга функцию зависимостью. Лучше объявите нужную функцию внутри эффекта:
16081608

16091609
<Sandpack>
16101610

@@ -1633,7 +1633,7 @@ function ChatRoom({ roomId }) {
16331633
16341634
return (
16351635
<>
1636-
<h1>Welcome to the {roomId} room!</h1>
1636+
<h1>Добро пожаловать в {roomId}!</h1>
16371637
<input value={message} onChange={e => setMessage(e.target.value)} />
16381638
</>
16391639
);
@@ -1644,7 +1644,7 @@ export default function App() {
16441644
return (
16451645
<>
16461646
<label>
1647-
Choose the chat room:{' '}
1647+
Выберите чат:{' '}
16481648
<select
16491649
value={roomId}
16501650
onChange={e => setRoomId(e.target.value)}
@@ -1663,13 +1663,13 @@ export default function App() {
16631663

16641664
```js chat.js
16651665
export function createConnection({ serverUrl, roomId }) {
1666-
// A real implementation would actually connect to the server
1666+
// В реальной реализации здесь было бы настоящее подключение к серверу
16671667
return {
16681668
connect() {
1669-
console.log('Connecting to "' + roomId + '" room at ' + serverUrl + '...');
1669+
console.log('✅ Подключение к чату "' + roomId + '" на ' + serverUrl + '...');
16701670
},
16711671
disconnect() {
1672-
console.log('Disconnected from "' + roomId + '" room at ' + serverUrl);
1672+
console.log('❌ Отключение от чата "' + roomId + '" на ' + serverUrl);
16731673
}
16741674
};
16751675
}
@@ -1682,7 +1682,7 @@ button { margin-left: 10px; }
16821682

16831683
</Sandpack>
16841684

1685-
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)
16861686

16871687
---
16881688

0 commit comments

Comments
 (0)