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
+39-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`es para autores de bibliotecas CSS-en-JS. A menos que estés trabajando en una biblioteca CSS-en-JS y necesites un lugar donde inyectar los estilos, probablemente busques [`useEffect`](/reference/react/useEffect)o[`useLayoutEffect`](/reference/react/useLayoutEffect)en su lugar.
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`es una versión de[`useEffect`](/reference/react/useEffect)que se dispara antes de cualquier mutación del DOM.
Call `useInsertionEffect`to insert the styles before any DOM mutations:
29
+
Llama a `useInsertionEffect`para insertar los estilos antes de cualquier mutación en el DOM:
30
30
31
31
```js
32
32
import { useInsertionEffect } from'react';
33
33
34
-
//Inside your CSS-in-JS library
34
+
//Dentro de tu biblioteca CSS-en-JS
35
35
functionuseCSS(rule) {
36
36
useInsertionEffect(() => {
37
-
// ... inject <style> tags here ...
37
+
// ... inyecta las etiquetas <style> aquí ...
38
38
});
39
39
return rule;
40
40
}
41
41
```
42
42
43
-
[See more examples below.](#usage)
43
+
[Ver más ejemplos a continuación.](#usage)
44
44
45
-
#### Parameters {/*parameters*/}
45
+
#### Parámetros {/*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 first 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 one last time.
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.
47
+
* `setup`: La función con la lógica de tu Efecto. Tu función setup puede opcionalmente devolver una función de *limpieza*. Antes de que tu componente sea añadido primero al DOM, React ejecutará tu función setup. Después de cada re-renderizado con dependencias modificadas, React ejecutará primero la función de limpieza (si es que la habías incluido) con los valores antiguos y entonces ejecutará tu función setup con los nuevos valores. Antes de que tu componente sea eliminado del DOM, React ejecutará tu función de limpieza una última vez.
50
48
51
-
#### Returns {/*returns*/}
49
+
* ***opcional** `dependencias`: La lista de todos los valores reactivos referenciados dentro del el código de `setup`. Los valores reactivos incluyen props, estado y todas las variables y funciones declaradas directamente dentro del cuerpo de tu componente. Si tu linter está [configurado para React](/learn/editor-setup#linting), verificará que cada valor reactivo esté correctamente especificado como dependencia. La lista de dependencias tienen que tener un número constante de elementos y que sean escritos en línea como `[dep1, dep2, dep3]`. React comparará cada dependencia con su valor previo usando el algoritmo de comparación [`Object.is`](https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Object/is). Si no especificas ninguna dependencia, tu Efecto se volverá a ejecutar después de cada renderizado del componente.
52
50
53
-
`useInsertionEffect` returns `undefined`.
51
+
#### Devuelve {/*returns*/}
54
52
55
-
#### Caveats {/*caveats*/}
53
+
`useInsertionEffect` devuelve `undefined`.
56
54
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.
55
+
#### Advertencias {/*caveats*/}
56
+
57
+
* Los Efectos que sólo se ejecutan en el cliente. No se ejecutan durante el renderizado en el servidor.
58
+
* No puedes actualizar el estado dentro de `useInsertionEffect`.
59
+
* En el tiempo en que `useInsertionEffect` se ejecuta, las referencias aún no han sido acopladas y el DOM todavía no ha sido actualizado.
60
60
61
61
---
62
62
63
-
## Usage {/*usage*/}
63
+
## Uso {/*usage*/}
64
64
65
-
### Injecting dynamic styles from CSS-in-JS libraries {/*injecting-dynamic-styles-from-css-in-js-libraries*/}
65
+
### Inyección de estilos dinámicos desde bibliotecas de CSS-en-JS {/_injecting-dynamic-styles-from-css-in-js-libraries_/} {/*inyección-de-estilos-dinámicos-desde-bibliotecas-de-css-en-js-injecting-dynamic-styles-from-css-in-js-libraries*/}
66
66
67
-
Traditionally, you would style React components using plain CSS.
67
+
Tradicionalmente, añadirías estilo a los componentes de React usando CSS plano.
68
68
69
69
```js
70
-
//In your JS file:
70
+
//En tu archivo JS:
71
71
<button className="success"/>
72
72
73
-
//In your CSS file:
73
+
//En tu archivo CSS:
74
74
.success { color: green; }
75
75
```
76
76
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:
77
+
Algunos equipos prefieren incluir sus estilos directamente en el código JavaScript en lugar de escribir archivos CSS. Esto normalmente requiere usar una biblioteca CSS-en-JS o una herramienta. Existen tres formas comunes de plantear el CSS-en-JS:
78
78
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
79
+
1. Extracción estática de archivos CSS con un compilador
80
+
2. Estilos en línea, ej. `<div style={{ opacity:1 }}>`
81
+
3. Inyección durante el runtime de las etiquetas `<style>`
82
82
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:**
83
+
Si usas CSS-en-JS, recomendamos la combinación de los dos primeros enfoques (archivos CSS para estilos estáticos, estilos en línea para estilos dinámicos). **No recomendamos la inyección durante el runtime de la etiqueta `<style>`por dos razones:**
84
84
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.
85
+
1. La inyección durante el runtime fuerza al navegador a recalcular los estilos mucho más a menudo.
86
+
2. La inyección durante el runtime puede ser muy lenta si ocurre en un tiempo inadecuado en el ciclo de vida de React.
87
87
88
-
The first problem is not solvable, but`useInsertionEffect`helps you solve the second problem.
88
+
El primer problema no se puede resolver, pero`useInsertionEffect`te ayuda a solucionar el segundo problema.
89
89
90
-
Call `useInsertionEffect`to insert the styles before any DOM mutations:
90
+
Llama a `useInsertionEffect`para insertar los estilos antes de cualquier mutación del DOM:
91
91
92
92
```js {4-11}
93
-
//Inside your CSS-in-JS library
93
+
//En tu biblioteca CSS-en-JS
94
94
let isInserted =newSet();
95
95
functionuseCSS(rule) {
96
96
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.
97
+
//Como hemos explicado antes, no recomendamos la inyección durante el runtime de las etiquetas <style>.
98
+
//Pero si tienes que hacerlo, entonces es importante que sea dentro del useInsertionEffect.
99
99
if (!isInserted.has(rule)) {
100
100
isInserted.add(rule);
101
101
document.head.appendChild(getStyleForRule(rule));
@@ -110,7 +110,7 @@ function Button() {
110
110
}
111
111
```
112
112
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:
113
+
De forma similar a `useEffect`, `useInsertionEffect`no se ejecuta en el servidor. Si tienes que agrupar las reglas CSS has usado en el servidor, puedes hacerlo durante el renderizado:
114
114
115
115
```js {1,4-6}
116
116
let collectedRulesSet =newSet();
@@ -126,14 +126,14 @@ function useCSS(rule) {
126
126
}
127
127
```
128
128
129
-
[Read more about upgrading CSS-in-JS libraries with runtime injection to`useInsertionEffect`.](https://github.com/reactwg/react-18/discussions/110)
129
+
[Lee más sobre actualizar bibliotecas CSS-en-JS con la inyección en runtime`useInsertionEffect`.](https://github.com/reactwg/react-18/discussions/110)
130
130
131
131
<DeepDive>
132
132
133
-
#### How is this better than injecting styles during rendering or useLayoutEffect? {/*how-is-this-better-than-injecting-styles-during-rendering-or-uselayouteffect*/}
133
+
#### ¿Cómo puede ser esto mejor que inyectar estilos durante el renderizado o useLayoutEffect? {/*how-is-this-better-than-injecting-styles-during-rendering-or-uselayouteffect*/}
134
134
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.**
135
+
Si insertas los estilos durante el renderizado y React está procesando una [actualización no bloqueante,](/reference/react/useTransition#marking-a-state-update-as-a-non-blocking-transition) el navegador recalculará los estilos en cada frame mientras renderiza un árbol de componentes, lo que puede ser **extremadamente lento.**
136
136
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.
137
+
`useInsertionEffect`es mejor que insertar estilos durante [`useLayoutEffect`](/reference/react/useLayoutEffect) o [`useEffect`](/reference/react/useEffect) porque asegura que en el tiempo en que otros Efectos se ejecuten en tus componentes, las etiquetas `<style>`ya han sido añadidas. De otro modo, los cálculos de layout en Efectos regulares podrían ser incorrectos por los estilos desactualizados.
0 commit comments