Skip to content

Commit 54290da

Browse files
committed
Translate useInsertionEffect
1 parent 426d0a2 commit 54290da

File tree

1 file changed

+38
-39
lines changed

1 file changed

+38
-39
lines changed

src/content/reference/react/useInsertionEffect.md

Lines changed: 38 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,13 @@ title: useInsertionEffect
44

55
<Pitfall>
66

7-
`useInsertionEffect` is for CSS-in-JS library authors. Unless you are working on a CSS-in-JS library and need a place to inject the styles, you probably want [`useEffect`](/reference/react/useEffect) or [`useLayoutEffect`](/reference/react/useLayoutEffect) instead.
7+
`useInsertionEffect` предназначен для авторов библиотек CSS-in-JS. Если вы не работаете над библиотекой CSS-in-JS и вам не нужно место для внедреня стилей, вам вероятно понадобится [`useEffect`](/reference/react/useEffect) или [`useLayoutEffect`](/reference/react/useLayoutEffect).
88

99
</Pitfall>
1010

1111
<Intro>
1212

13-
`useInsertionEffect` is a version of [`useEffect`](/reference/react/useEffect) that fires before any DOM mutations.
13+
`useInsertionEffect` это версия [`useEffect`](/reference/react/useEffect) которая срабатывает перед любыми изменениями DOM.
1414

1515
```js
1616
useInsertionEffect(setup, dependencies?)
@@ -22,80 +22,79 @@ useInsertionEffect(setup, dependencies?)
2222
2323
---
2424
25-
## Reference {/*reference*/}
25+
## Справочник {/*reference*/}
2626
2727
### `useInsertionEffect(setup, dependencies?)` {/*useinsertioneffect*/}
2828
29-
Call `useInsertionEffect` to insert the styles before any DOM mutations:
29+
Вызовите `useInsertionEffect` чтобы вставить стили перед любыми мутациями DOM:
3030
3131
```js
3232
import { useInsertionEffect } from 'react';
3333

34-
// Inside your CSS-in-JS library
34+
// Внутри вашей бибилиотеки CSS-in-JS
3535
function useCSS(rule) {
3636
useInsertionEffect(() => {
37-
// ... inject <style> tags here ...
37+
// ... вставьте свои теги <style> сюда ...
3838
});
3939
return rule;
4040
}
4141
```
4242
43-
[See more examples below.](#usage)
43+
[Больше примеров ниже.](#usage)
4444
45-
#### Parameters {/*parameters*/}
45+
#### Параметры {/*parameters*/}
4646
47-
* `setup`: The function with your Effect's logic. Your setup function may also optionally return a *cleanup* function. Before your component is added to the DOM, React will run your setup function. After every re-render with changed dependencies, React will first run the cleanup function (if you provided it) with the old values, and then run your setup function with the new values. Before your component is removed from the DOM, React will run your cleanup function.
47+
* `setup`: Функция с логикой вашего эффекта. Ваша setup функция, опционально, может возвращать функцию *очистки*. Перед тем, как ваш компонент добавится в DOM, реакт запустит вашу setup фнукцию. После каждого повторного рендеринга с измененными зависимостями, реакт запустит функцию очистки (если вы ее предоставили) со старыми заничениями, а затем запустит вашу setup функцию с новыми значениями. Перед тем как ваш компонент удалится из DOM, реакт запустит функцию очистки.
4848
49-
* **optional** `dependencies`: The list of all reactive values referenced inside of the `setup` code. Reactive values include props, state, and all the variables and functions declared directly inside your component body. If your linter is [configured for React](/learn/editor-setup#linting), it will verify that every reactive value is correctly specified as a dependency. The list of dependencies must have a constant number of items and be written inline like `[dep1, dep2, dep3]`. React will compare each dependency with its previous value using the [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison algorithm. If you don't specify the dependencies at all, your Effect will re-run after every re-render of the component.
49+
* `dependencies`: Список всех реактивных значений, на которые ссылается код функции `setup`. К реактивным значениям относятся реквизиты, состояние, а также все переменные и функции, объявленные непосредственно в теле компонента. Если ваш линтер [настроен для использования с React](/learn/editor-setup#linting), он проверит, что каждое реактивное значение правильно указано как зависимость. Список зависимостей должен иметь постоянное количество элементов и быть написан inline по типу `[dep1, dep2, dep3]`. React будет сравнивать каждую зависимость с предыдущим значением, используя алгоритм сравнения [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). Если не указать зависимости вообще, то эффект запустится заново после каждого повторного рендеринга компонента.
5050
51-
#### Returns {/*returns*/}
51+
#### Возвращаемое значение {/*returns*/}
5252
53-
`useInsertionEffect` returns `undefined`.
53+
`useInsertionEffect` возвращает `undefined`.
5454
55-
#### Caveats {/*caveats*/}
55+
#### Предостережения {/*caveats*/}
5656
57-
* Effects only run on the client. They don't run during server rendering.
58-
* You can't update state from inside `useInsertionEffect`.
59-
* By the time `useInsertionEffect` runs, refs are not attached yet, and DOM is not yet updated.
57+
* Эффекты выполняются только на клиенте. Они не выполняются во время серверного рендеринга.
58+
* Вы не можете обновить состояние изнутри `useInsertionEffect`.
59+
* К моменту выполнения `useInsertionEffect` ссылки еще не прикреплены, а DOM еще не обновлен.
6060
6161
---
6262
63-
## Usage {/*usage*/}
63+
## Использование {/*usage*/}
6464
65-
### Injecting dynamic styles from CSS-in-JS libraries {/*injecting-dynamic-styles-from-css-in-js-libraries*/}
65+
### Внедрение динамических стилей из библиотек CSS-in-JS {/*injecting-dynamic-styles-from-css-in-js-libraries*/}
6666
67-
Traditionally, you would style React components using plain CSS.
67+
Традиционно для стилизации компонентов React используется обычный CSS.
6868
6969
```js
70-
// In your JS file:
70+
// В вашем JS файле:
7171
<button className="success" />
7272

73-
// In your CSS file:
73+
// В вашем CSS файле:
7474
.success { color: green; }
7575
```
76+
Некоторые команды предпочитают создавать стили непосредственно в коде JavaScript, вместо того чтобы писать файлы CSS. Обычно это требует использования библиотеки или инструмента CSS-in-JS. Существует три распространённых подхода к CSS-in-JS:
7677
77-
Some teams prefer to author styles directly in JavaScript code instead of writing CSS files. This usually requires using a CSS-in-JS library or a tool. There are three common approaches to CSS-in-JS:
78+
1. Статическая экстракция в файлы CSS с помощью компилятора
79+
2. Инлайн стили, например, `<div style={{ opacity: 1 }}>`
80+
3. Внедрение тегов `<style>` во время выполнения.
7881
79-
1. Static extraction to CSS files with a compiler
80-
2. Inline styles, e.g. `<div style={{ opacity: 1 }}>`
81-
3. Runtime injection of `<style>` tags
82+
Если вы используете CSS-in-JS, мы рекомендуем комбинацию первых двух подходов (файлы CSS для статических стилей, инлайн стили для динамических стилей). Мы не рекомендуем внедрение тегов `<style>` во время выполнения по двум причинам:
8283
83-
If you use CSS-in-JS, we recommend a combination of the first two approaches (CSS files for static styles, inline styles for dynamic styles). **We don't recommend runtime `<style>` tag injection for two reasons:**
84+
1. Внедрение во время выполнения заставляет браузер пересчитывать стили гораздо чаще.
85+
2. Внедрение может быть очень медленным, если это происходит в неподходящее время жизненного цикла React.
8486
85-
1. Runtime injection forces the browser to recalculate the styles a lot more often.
86-
2. Runtime injection can be very slow if it happens at the wrong time in the React lifecycle.
87+
Первая проблема неразрешима, но `useInsertionEffect` помогает решить вторую проблему.
8788
88-
The first problem is not solvable, but `useInsertionEffect` helps you solve the second problem.
89-
90-
Call `useInsertionEffect` to insert the styles before any DOM mutations:
89+
Вызовите `useInsertionEffect`, чтобы вставить стили до любых мутаций DOM:
9190
9291
```js {4-11}
93-
// Inside your CSS-in-JS library
92+
// Внутри вашей CSS-in-JS библиотеки
9493
let isInserted = new Set();
9594
function useCSS(rule) {
9695
useInsertionEffect(() => {
97-
// As explained earlier, we don't recommend runtime injection of <style> tags.
98-
// But if you have to do it, then it's important to do in useInsertionEffect.
96+
// Как было объяснено ранее, мы не рекомендуем внедрение тегов <style> во время выполнения.
97+
// Но если вам нужно это сделать, то важно использовать для этого useInsertionEffect.
9998
if (!isInserted.has(rule)) {
10099
isInserted.add(rule);
101100
document.head.appendChild(getStyleForRule(rule));
@@ -110,7 +109,7 @@ function Button() {
110109
}
111110
```
112111
113-
Similarly to `useEffect`, `useInsertionEffect` does not run on the server. If you need to collect which CSS rules have been used on the server, you can do it during rendering:
112+
Схожим образом `useEffect`, `useInsertionEffect` не запускается на сервере. Если вам нужно собрать информацию о том, какие CSS правила были использованы на сервере, вы можете сделать это во время рендеринга:
114113
115114
```js {1,4-6}
116115
let collectedRulesSet = new Set();
@@ -126,14 +125,14 @@ function useCSS(rule) {
126125
}
127126
```
128127
129-
[Read more about upgrading CSS-in-JS libraries with runtime injection to `useInsertionEffect`.](https://github.com/reactwg/react-18/discussions/110)
128+
[Читайте больше о том, как обновить библиотеки CSS-in-JS с внедрением во время выполнения до использования useInsertionEffect`.](https://github.com/reactwg/react-18/discussions/110)
130129

131130
<DeepDive>
132131

133-
#### How is this better than injecting styles during rendering or useLayoutEffect? {/*how-is-this-better-than-injecting-styles-during-rendering-or-uselayouteffect*/}
132+
#### Чем это лучше, чем внедрение стилей во время рендеринга или использование useLayoutEffect? {/*how-is-this-better-than-injecting-styles-during-rendering-or-uselayouteffect*/}
134133

135-
If you insert styles during rendering and React is processing a [non-blocking update,](/reference/react/useTransition#marking-a-state-update-as-a-non-blocking-transition) the browser will recalculate the styles every single frame while rendering a component tree, which can be **extremely slow.**
134+
Если вы вставляете стили во время рендеринга, и React обрабатывает [неблокирующее обновление,](/reference/react/useTransition#marking-a-state-update-as-a-non-blocking-transition) браузер будет пересчитывать стили на каждом кадре во время рендеринга дерева компонентов, что может быть **чрезвычайно медленным.**
136135

137-
`useInsertionEffect` is better than inserting styles during [`useLayoutEffect`](/reference/react/useLayoutEffect) or [`useEffect`](/reference/react/useEffect) because it ensures that by the time other Effects run in your components, the `<style>` tags have already been inserted. Otherwise, layout calculations in regular Effects would be wrong due to outdated styles.
136+
`useInsertionEffect` лучше, чем вставка стилей во время [`useLayoutEffect`](/reference/react/useLayoutEffect) или [`useEffect`](/reference/react/useEffect) потому что это гарантирует, что к тому времени, как другие эффекты запускаются в ваших компонентах, теги `<style>` уже будут вставлены. В противном случае расчеты компоновки в обычных эффектах будут неверными из-за устаревших стилей.
138137

139138
</DeepDive>

0 commit comments

Comments
 (0)