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/reference/react/useInsertionEffect.md
+38-39Lines changed: 38 additions & 39 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -4,13 +4,13 @@ title: useInsertionEffect
4
4
5
5
<Pitfall>
6
6
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).
8
8
9
9
</Pitfall>
10
10
11
11
<Intro>
12
12
13
-
`useInsertionEffect`is a version of [`useEffect`](/reference/react/useEffect)that fires before any DOM mutations.
13
+
`useInsertionEffect`это версия [`useEffect`](/reference/react/useEffect)которая срабатывает перед любыми изменениями DOM.
Call`useInsertionEffect`to insert the styles before any DOM mutations:
29
+
Вызовите`useInsertionEffect`чтобы вставить стили перед любыми мутациями DOM:
30
30
31
31
```js
32
32
import { useInsertionEffect } from'react';
33
33
34
-
//Inside your CSS-in-JS library
34
+
//Внутри вашей бибилиотеки CSS-in-JS
35
35
functionuseCSS(rule) {
36
36
useInsertionEffect(() => {
37
-
// ... inject <style> tags here ...
37
+
// ... вставьте свои теги <style> сюда ...
38
38
});
39
39
return rule;
40
40
}
41
41
```
42
42
43
-
[See more examples below.](#usage)
43
+
[Больше примеров ниже.](#usage)
44
44
45
-
#### Parameters {/*parameters*/}
45
+
#### Параметры {/*parameters*/}
46
46
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, реакт запустит функцию очистки.
48
48
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). Если не указать зависимости вообще, то эффект запустится заново после каждого повторного рендеринга компонента.
50
50
51
-
#### Returns {/*returns*/}
51
+
#### Возвращаемое значение {/*returns*/}
52
52
53
-
`useInsertionEffect`returns`undefined`.
53
+
`useInsertionEffect`возвращает`undefined`.
54
54
55
-
#### Caveats {/*caveats*/}
55
+
#### Предостережения {/*caveats*/}
56
56
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 еще не обновлен.
60
60
61
61
---
62
62
63
-
## Usage {/*usage*/}
63
+
## Использование {/*usage*/}
64
64
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*/}
66
66
67
-
Traditionally, you would style React components using plain CSS.
67
+
Традиционно для стилизации компонентов React используется обычный CSS.
68
68
69
69
```js
70
-
//In your JS file:
70
+
//В вашем JS файле:
71
71
<button className="success"/>
72
72
73
-
//In your CSS file:
73
+
//В вашем CSS файле:
74
74
.success { color: green; }
75
75
```
76
+
Некоторые команды предпочитают создавать стили непосредственно в коде JavaScript, вместо того чтобы писать файлы CSS. Обычно это требует использования библиотеки или инструмента CSS-in-JS. Существует три распространённых подхода к CSS-in-JS:
76
77
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>` во время выполнения.
78
81
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>` во время выполнения по двум причинам:
82
83
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.
84
86
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` помогает решить вторую проблему.
87
88
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:
91
90
92
91
```js {4-11}
93
-
//Inside your CSS-in-JS library
92
+
//Внутри вашей CSS-in-JS библиотеки
94
93
let isInserted =newSet();
95
94
functionuseCSS(rule) {
96
95
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.
99
98
if (!isInserted.has(rule)) {
100
99
isInserted.add(rule);
101
100
document.head.appendChild(getStyleForRule(rule));
@@ -110,7 +109,7 @@ function Button() {
110
109
}
111
110
```
112
111
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 правила были использованы на сервере, вы можете сделать это во время рендеринга:
114
113
115
114
```js {1,4-6}
116
115
let collectedRulesSet =newSet();
@@ -126,14 +125,14 @@ function useCSS(rule) {
126
125
}
127
126
```
128
127
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)
130
129
131
130
<DeepDive>
132
131
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*/}
134
133
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) браузер будет пересчитывать стили на каждом кадре во время рендеринга дерева компонентов, что может быть**чрезвычайно медленным.**
136
135
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>`уже будут вставлены. В противном случае расчеты компоновки в обычных эффектах будут неверными из-за устаревших стилей.
0 commit comments