Skip to content

Commit 17f83eb

Browse files
docs(pt-br): translate useInsertionEffect page (#761)
* feat: add translation of useInsertionEffect into pt-br * fix * fix * Update useInsertionEffect.md
1 parent 329bae7 commit 17f83eb

File tree

1 file changed

+40
-39
lines changed

1 file changed

+40
-39
lines changed

src/content/reference/react/useInsertionEffect.md

+40-39
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` é 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.
88

99
</Pitfall>
1010

1111
<Intro>
1212

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.
1414

1515
```js
1616
useInsertionEffect(setup, dependencies?)
@@ -22,81 +22,82 @@ useInsertionEffect(setup, dependencies?)
2222
2323
---
2424
25-
## Reference {/*reference*/}
25+
## Referência {/*reference*/}
2626
2727
### `useInsertionEffect(setup, dependencies?)` {/*useinsertioneffect*/}
2828
29-
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:
3030
3131
```js
3232
import { useInsertionEffect } from 'react';
3333

34-
// Inside your CSS-in-JS library
34+
// Na sua biblioteca CSS-em-JS
3535
function useCSS(rule) {
3636
useInsertionEffect(() => {
37-
// ... inject <style> tags here ...
37+
// ... injetar tags <style> aqui ...
3838
});
3939
return rule;
4040
}
4141
```
4242
43-
[See more examples below.](#usage)
43+
[Veja mais exemplos abaixo.](#usage)
4444
4545
#### Parameters {/*parameters*/}
4646
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.
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+
* **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.
5050
51-
#### Returns {/*returns*/}
51+
#### Retornos {/*returns*/}
5252
53-
`useInsertionEffect` returns `undefined`.
53+
`useInsertionEffect` retorna `undefined`.
5454
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.
5662
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.
6263
---
6364
64-
## Usage {/*usage*/}
65+
## Utilização {/*usage*/}
6566
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*/}
6768
68-
Traditionally, you would style React components using plain CSS.
69+
Tradicionalmente, você estilizaria componentes React usando CSS simples.
6970
7071
```js
71-
// In your JS file:
72+
// Em seu arquivo JS:
7273
<button className="success" />
7374

74-
// In your CSS file:
75+
// Em seu arquivo CSS:
7576
.success { color: green; }
7677
```
7778
78-
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:
7980
80-
1. Static extraction to CSS files with a compiler
81-
2. Inline styles, e.g. `<div style={{ opacity: 1 }}>`
82-
3. Runtime injection of `<style>` tags
81+
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>`
8384
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:**
8586
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.
8889
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.
9091
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:
9293
9394
```js {4-11}
94-
// Inside your CSS-in-JS library
95+
// Dentro da sua biblioteca CSS-em-JS
9596
let isInserted = new Set();
9697
function useCSS(rule) {
9798
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.
100101
if (!isInserted.has(rule)) {
101102
isInserted.add(rule);
102103
document.head.appendChild(getStyleForRule(rule));
@@ -111,7 +112,7 @@ function Button() {
111112
}
112113
```
113114
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:
115116
116117
```js {1,4-6}
117118
let collectedRulesSet = new Set();
@@ -127,14 +128,14 @@ function useCSS(rule) {
127128
}
128129
```
129130
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)
131132
132133
<DeepDive>
133134
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*/}
135136
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**.
137138
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
139140
140141
</DeepDive>

0 commit comments

Comments
 (0)