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
+40-39
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`é destinado a autores de bibliotecas CSS-em-JS. A menos que você esteja desenvolvendo em uma biblioteca CSS-em-JS e precise injetar os estilos, você provavelmente vai utilizar [`useEffect`](/reference/react/useEffect)ou[`useLayoutEffect`](/reference/react/useLayoutEffect)em vez disso.
8
8
9
9
</Pitfall>
10
10
11
11
<Intro>
12
12
13
-
`useInsertionEffect`allows inserting elements into the DOM before any layout Effects fire.
13
+
O `useInsertionEffect`permite inserir elementos no DOM antes que qualquer efeito de layout seja acionado.
Call `useInsertionEffect` to insert styles before any Effects fire that may need to read layout:
29
+
Chame useInsertionEffect para inserir estilos antes que quaisquer efeitos sejam ativados e que possam precisar ler o layout:
30
30
31
31
```js
32
32
import { useInsertionEffect } from'react';
33
33
34
-
//Inside your CSS-in-JS library
34
+
//Na sua biblioteca CSS-em-JS
35
35
functionuseCSS(rule) {
36
36
useInsertionEffect(() => {
37
-
// ... inject <style> tags here ...
37
+
// ... injetar tags <style> aqui ...
38
38
});
39
39
return rule;
40
40
}
41
41
```
42
42
43
-
[See more examples below.](#usage)
43
+
[Veja mais exemplos abaixo.](#usage)
44
44
45
45
#### Parameters {/*parameters*/}
46
46
47
-
* `setup`: The function with your Effect's logic. Your setup function may also optionally return a *cleanup* function. When your component is added to the DOM, but before any layout Effects fire, 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. When your component is removed from the DOM, React will run your cleanup function.
47
+
* `setup`: A função que contém a lógica do seu Effect. A função de setup também pode opcionalmente retornar uma função *cleanup*. Quando o componente é adicionado ao DOM, porém antes de qualquer efeito de layout ser acionado, o React executará sua função de setup. Após cada re-renderização com as dependências alteradas, o React irá executar primeiro a função de cleanup (caso você a tenha fornecido) com os valores antigos, e depois executará sua função de setup com os novos valores. Quando o componente for removido do DOM, o React irá executar sua função de cleanup.
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
+
* **opcional** `dependencies`: A lista de todos os valores reativos referenciados no código`setup`. Valores reativos incluem props, state, e todas as variáveis e funções declaradas diretamente dentro do corpo do seu componente. Caso seu linter esteja [configurado para React](/learn/editor-setup#linting), ele irá verificar se cada valor reativo está corretamente especificado como uma dependência. A lista de dependências deve ter um número constante de itens e ser escrita em linha como `[dep1, dep2, dep3]`. O React irá comparar cada dependência com seu valor anterior utilizando o algoritmo de comparação [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). Se você não especificar as dependências, seu Effect será executado novamente após cada re-renderização do componente.
50
50
51
-
#### Returns {/*returns*/}
51
+
#### Retornos {/*returns*/}
52
52
53
-
`useInsertionEffect`returns`undefined`.
53
+
`useInsertionEffect`retorna`undefined`.
54
54
55
-
#### Caveats {/*caveats*/}
55
+
#### Avisos {/*caveats*/}
56
+
57
+
* Effects (efeitos) só são executados pelo cliente. Eles não são executados durante a renderização do servidor.
58
+
* Não é possível atualizar o estado de dentro do `useInsertionEffect`.
59
+
* No momento em que `useInsertionEffect` é executado, as refs ainda não foram anexadas.
60
+
* O `useInsertionEffect` pode ser utilizado antes ou depois do DOM ter sido atualizado. Você não deve confiar que o DOM seja atualizado em um determinado momento.
61
+
* Ao contrário de outros tipos de Effects, que disparam a limpeza para cada Effect e depois a configuração para cada Effect, `useInsertionEffect` irá disparar tanto a limpeza quanto a configuração de um componente de cada vez. Isso resulta em uma “intercalação” das funções de limpeza e configuração.
56
62
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.
60
-
* `useInsertionEffect` may run either before or after the DOM has been updated. You shouldn't rely on the DOM being updated at any particular time.
61
-
* Unlike other types of Effects, which fire cleanup for every Effect and then setup for every Effect, `useInsertionEffect` will fire both cleanup and setup one component at a time. This results in an "interleaving" of the cleanup and setup functions.
62
63
---
63
64
64
-
## Usage {/*usage*/}
65
+
## Utilização {/*usage*/}
65
66
66
-
### Injecting dynamic styles from CSS-in-JS libraries {/*injecting-dynamic-styles-from-css-in-js-libraries*/}
67
+
### Injetar os estilos dinâmicos em bibliotecas CSS-em-JS {/*injecting-dynamic-styles-from-css-em-js-libraries*/}
67
68
68
-
Traditionally, you would style React components using plain CSS.
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:
79
+
Algumas equipes preferem criar estilos diretamente no código JavaScript em vez de escrever arquivos CSS. Isso geralmente requer o uso de uma biblioteca CSS-em-JS ou de alguma ferramenta. Existem três abordagens comuns para CSS-em-JS:
1. A extração estática para os arquivos CSS por um compilador
82
+
2. Estilos em linha, por exemplo,`<div style={{ opacity:1 }}>`
83
+
3. Injeção em tempo de execução de tags `<style>`
83
84
84
-
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:**
85
+
Se utilizar CSS-em-JS, é recomendável uma combinação das duas primeiras abordagens (arquivos CSS para estilos estáticos, e estilos inline para estilos dinâmicos). **Não recomendamos a injeção de tag em tempo de execução `<style>`por duas razões:**
85
86
86
-
1. Runtime injection forces the browser to recalculate the styles a lot more often.
87
-
2. Runtime injection can be very slow if it happens at the wrong time in the React lifecycle.
87
+
1. A injeção em tempo de execução obriga o navegador a recalcular os estilos com muito mais frequência.
88
+
2. A injeção em tempo de execução pode ser muito lenta se ocorrer no tempo errado no ciclo de vida do React.
88
89
89
-
The first problem is not solvable, but `useInsertionEffect`helps you solve the second problem.
90
+
O primeiro problema não tem solução, mas o `useInsertionEffect`pode ajudar a resolver o segundo problema.
90
91
91
-
Call`useInsertionEffect`to insert the styles before any layout Effects fire:
92
+
Chame`useInsertionEffect`para inserir os estilos antes que quaisquer efeitos de layout sejam acionados:
92
93
93
94
```js {4-11}
94
-
//Inside your CSS-in-JS library
95
+
//Dentro da sua biblioteca CSS-em-JS
95
96
let isInserted =newSet();
96
97
functionuseCSS(rule) {
97
98
useInsertionEffect(() => {
98
-
//As explained earlier, we don't recommend runtime injection of <style> tags.
99
-
//But if you have to do it, then it's important to do in useInsertionEffect.
99
+
//Como explicado anteriormente, nós não recomendamos injeção em tempo de execução de tags <style>.
100
+
//Porém, se precisar ser feito, é importante que seja feito em useInsertionEffect.
100
101
if (!isInserted.has(rule)) {
101
102
isInserted.add(rule);
102
103
document.head.appendChild(getStyleForRule(rule));
@@ -111,7 +112,7 @@ function Button() {
111
112
}
112
113
```
113
114
114
-
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:
115
+
Da mesma forma que `useEffect`, `useInsertionEffect`não é executado no servidor. Caso seja necessário coletar as regras CSS que foram utilizadas no servidor, isso pode ser feito durante a renderização:
115
116
116
117
```js {1,4-6}
117
118
let collectedRulesSet =newSet();
@@ -127,14 +128,14 @@ function useCSS(rule) {
127
128
}
128
129
```
129
130
130
-
[Read more about upgrading CSS-in-JS libraries with runtime injection to`useInsertionEffect`.](https://github.com/reactwg/react-18/discussions/110)
131
+
[Saiba mais sobre a atualização das bibliotecas CSS-em-JS com injeção em tempo de execução para`useInsertionEffect`.](https://github.com/reactwg/react-18/discussions/110)
131
132
132
133
<DeepDive>
133
134
134
-
#### How is this better than injecting styles during rendering or useLayoutEffect? {/*how-is-this-better-than-injecting-styles-during-rendering-or-uselayouteffect*/}
135
+
#### Como isso é melhor do que injetar estilos durante a renderização ou useLayoutEffect? {/*how-is-this-better-than-emjecting-styles-during-rendering-or-uselayouteffect*/}
135
136
136
-
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.**
137
+
Caso insira estilos durante a renderização e o React esteja a executar uma [atualização não bloqueante,](/reference/react/useTransition#marking-a-state-update-as-a-non-blocking-transition) o navegador irá recalcular os estilos a cada frame enquanto renderiza uma estrutura de componentes, o que pode ser **extremamente lento**.
137
138
138
-
`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.
139
+
O `useInsertionEffect`é melhor do do que inserir estilos durante o [`useLayoutEffect`](/reference/react/useLayoutEffect) ou [`useEffect`](/reference/react/useEffect) porque ele garante que no momento em que outros efeitos forem executados em seus componentes, as tags `<style>`já estarão inseridas. Caso contrário, os cálculos de layout em Effects comuns estariam errados devido a estilos desatualizados
0 commit comments