Skip to content

Commit b57a91a

Browse files
carlos-garcia-devcarburo
authored andcommitted
translate useInsertionEffet reference page
closes #642
1 parent c61d5b4 commit b57a91a

File tree

1 file changed

+39
-39
lines changed

1 file changed

+39
-39
lines changed

Diff for: src/content/reference/react/useInsertionEffect.md

+39-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` 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.
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` es una versión de [`useEffect`](/reference/react/useEffect) que se dispara antes de cualquier mutación del DOM.
1414

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

34-
// Inside your CSS-in-JS library
34+
// Dentro de tu biblioteca CSS-en-JS
3535
function useCSS(rule) {
3636
useInsertionEffect(() => {
37-
// ... inject <style> tags here ...
37+
// ... inyecta las etiquetas <style> aquí ...
3838
});
3939
return rule;
4040
}
4141
```
4242
43-
[See more examples below.](#usage)
43+
[Ver más ejemplos a continuación.](#usage)
4444
45-
#### Parameters {/*parameters*/}
45+
#### Parámetros {/*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 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.
5048
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.
5250
53-
`useInsertionEffect` returns `undefined`.
51+
#### Devuelve {/*returns*/}
5452
55-
#### Caveats {/*caveats*/}
53+
`useInsertionEffect` devuelve `undefined`.
5654
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.
6060
6161
---
6262
63-
## Usage {/*usage*/}
63+
## Uso {/*usage*/}
6464
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*/}
6666
67-
Traditionally, you would style React components using plain CSS.
67+
Tradicionalmente, añadirías estilo a los componentes de React usando CSS plano.
6868
6969
```js
70-
// In your JS file:
70+
// En tu archivo JS:
7171
<button className="success" />
7272

73-
// In your CSS file:
73+
// En tu archivo CSS:
7474
.success { color: green; }
7575
```
7676
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:
7878
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>`
8282
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:**
8484
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.
8787
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.
8989
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:
9191
9292
```js {4-11}
93-
// Inside your CSS-in-JS library
93+
// En tu biblioteca CSS-en-JS
9494
let isInserted = new Set();
9595
function useCSS(rule) {
9696
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.
9999
if (!isInserted.has(rule)) {
100100
isInserted.add(rule);
101101
document.head.appendChild(getStyleForRule(rule));
@@ -110,7 +110,7 @@ function Button() {
110110
}
111111
```
112112
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:
114114
115115
```js {1,4-6}
116116
let collectedRulesSet = new Set();
@@ -126,14 +126,14 @@ function useCSS(rule) {
126126
}
127127
```
128128
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)
130130
131131
<DeepDive>
132132
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*/}
134134
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.**
136136
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.
138138
139139
</DeepDive>

0 commit comments

Comments
 (0)