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
You are probably here because you got the following error message:
5
+
Probablemente estás aquí porque te ha aparecido el siguiente mensaje de error:
6
6
7
7
<ConsoleBlocklevel="error">
8
8
9
9
Hooks can only be called inside the body of a function component.
10
10
11
11
</ConsoleBlock>
12
12
13
-
There are three common reasons you might be seeing it:
13
+
Este mensaje puede aparecer por tres motivos comunes:
14
14
15
-
1.You might be **breaking the Rules of Hooks**.
16
-
2.You might have **mismatching versions**of React and React DOM.
17
-
3.You might have **more than one copy of React**in the same app.
15
+
1.Estás **incumpliendo las Reglas de los Hooks**.
16
+
2.Estás usando **versiones incompatibles**de React y React DOM.
17
+
3.Estás usando **más de una instancia de React**en la misma aplicación.
18
18
19
-
Let's look at each of these cases.
19
+
Veamos cada uno de estos casos.
20
20
21
-
## Breaking Rules of Hooks {/*breaking-rules-of-hooks*/}
21
+
## Incumplir las Reglas de los Hooks {/*breaking-rules-of-hooks*/}
22
22
23
-
Functions whose names start with`use`are called [*Hooks*](/reference/react)in React.
23
+
Las funciones que comienzan con`use`se conocen como [*Hooks*](/reference/react)en React.
24
24
25
-
**Don’t call Hooks inside loops, conditions, or nested functions.**Instead, always use Hooks at the top level of your React function, before any early returns. You can only call Hooks while React is rendering a function component:
25
+
**Evita utilizar Hooks dentro de ciclos, condicionales o funciones anidadas.**En su lugar, utiliza los Hooks únicamente en el nivel superior de tu función de React, antes de cualquier retorno anticipado. Los Hooks sólo deben ser utilizados durante la renderización de un componente de función en React:
26
26
27
-
* ✅ Call them at the top level in the body of a [function component](/learn/your-first-component).
28
-
* ✅ Call them at the top level in the body of a [custom Hook](/learn/reusing-logic-with-custom-hooks).
27
+
* ✅ Utilízalos en el nivel superior del cuerpo de un [componente de función](/learn/your-first-component).
28
+
* ✅ Utilízalos en el nivel superior del cuerpo de un [Hook personalizado](/learn/reusing-logic-with-custom-hooks).
29
29
30
30
```js{2-3,8-9}
31
31
function Counter() {
32
-
// ✅ Good: top-level in a function component
32
+
// ✅ Correcto: en la parte superior de un componente de función
33
33
const [count, setCount] = useState(0);
34
34
// ...
35
35
}
36
36
37
37
function useWindowWidth() {
38
-
// ✅ Good: top-level in a custom Hook
38
+
// ✅ Correcto: en la parte superior de un Hook personalizado
It’s **not**supported to call Hooks (functions starting with `use`) in any other cases, for example:
44
+
No se **permite**el uso de Hooks (funciones que comienzan con `use`) en ningún otro caso, por ejemplo:
45
45
46
-
* 🔴 Do not call Hooks inside conditions or loops.
47
-
* 🔴 Do not call Hooks after a conditional `return`statement.
48
-
* 🔴 Do not call Hooks in event handlers.
49
-
* 🔴 Do not call Hooks in class components.
50
-
* 🔴 Do not call Hooks inside functions passed to `useMemo`, `useReducer`, or`useEffect`.
46
+
* 🔴 Dentro de condicionales o ciclos.
47
+
* 🔴 Despúes de una declaración de `return`condicional.
48
+
* 🔴 En manejadores de eventos.
49
+
* 🔴 En componentes de clase.
50
+
* 🔴 Dentro de funciones pasadas a `useMemo`, `useReducer`, o`useEffect`.
51
51
52
-
If you break these rules, you might see this error.
52
+
Incumplir estas reglas podría provocar la aparición de este error.
53
53
54
54
```js{3-4,11-12,20-21}
55
55
function Bad({ cond }) {
56
56
if (cond) {
57
-
// 🔴 Bad: inside a condition (to fix, move it outside!)
57
+
// 🔴 Incorrecto: dentro de una condicional (para solucionarlo, ¡colócalo fuera!)
58
58
const theme = useContext(ThemeContext);
59
59
}
60
60
// ...
61
61
}
62
62
63
63
function Bad() {
64
64
for (let i = 0; i < 10; i++) {
65
-
// 🔴 Bad: inside a loop (to fix, move it outside!)
65
+
// 🔴 Incorrecto: dentro de un ciclo (para solucionarlo, ¡colócalo fuera!)
66
66
const theme = useContext(ThemeContext);
67
67
}
68
68
// ...
@@ -72,22 +72,22 @@ function Bad({ cond }) {
72
72
if (cond) {
73
73
return;
74
74
}
75
-
// 🔴 Bad: after a conditional return (to fix, move it before the return!)
75
+
// 🔴 Incorrecto: después de un retorno condicional (para solucionarlo, ¡colócalo antes del retorno!)
76
76
const theme = useContext(ThemeContext);
77
77
// ...
78
78
}
79
79
80
80
function Bad() {
81
81
function handleClick() {
82
-
// 🔴 Bad: inside an event handler (to fix, move it outside!)
82
+
// 🔴 Incorrecto: dentro de un manejador de eventos (para solucionarlo, ¡colócalo fuera!)
83
83
const theme = useContext(ThemeContext);
84
84
}
85
85
// ...
86
86
}
87
87
88
88
function Bad() {
89
89
const style = useMemo(() => {
90
-
// 🔴 Bad: inside useMemo (to fix, move it outside!)
90
+
// 🔴 Incorrecto: dentro de useMemo (para solucionarlo, ¡colócalo fuera!)
91
91
const theme = useContext(ThemeContext);
92
92
return createStyle(theme);
93
93
});
@@ -96,63 +96,63 @@ function Bad() {
96
96
97
97
class Bad extends React.Component {
98
98
render() {
99
-
// 🔴 Bad: inside a class component (to fix, write a function component instead of a class!)
99
+
// 🔴 Incorrecto: dentro de un componente de clase (para solucionarlo, ¡escribe un componente de función en lugar de uno de clase!)
100
100
useEffect(() => {})
101
101
// ...
102
102
}
103
103
}
104
104
```
105
105
106
-
You can use the [`eslint-plugin-react-hooks` plugin](https://www.npmjs.com/package/eslint-plugin-react-hooks)to catch these mistakes.
106
+
Puedes usar el [plugin de `eslint-plugin-react-hooks`](https://www.npmjs.com/package/eslint-plugin-react-hooks)para detectar estos errores.
107
107
108
108
<Note>
109
109
110
-
[Custom Hooks](/learn/reusing-logic-with-custom-hooks)*may* call other Hooks (that's their whole purpose). This works because custom Hooks are also supposed to only be called while a function component is rendering.
110
+
Los [Hooks personalizados](/learn/reusing-logic-with-custom-hooks)*pueden* llamar a otros Hooks (ese es su propósito principal). Esto es posible porque los Hooks personalizados también deben ser llamados sólo durante la renderización de un componente de función.
111
111
112
112
</Note>
113
113
114
-
## Mismatching Versions of React and React DOM {/*mismatching-versions-of-react-and-react-dom*/}
114
+
## Uso de versiones incompatibles de React y React DOM {/*mismatching-versions-of-react-and-react-dom*/}
115
115
116
-
You might be using a version of`react-dom` (< 16.8.0) or`react-native` (< 0.59) that doesn't yet support Hooks. You can run `npm ls react-dom`or`npm ls react-native`in your application folder to check which version you're using. If you find more than one of them, this might also create problems (more on that below).
116
+
Puede que estés usando versiones antiguas de`react-dom` (< 16.8.0) o`react-native` (< 0.59) que no sean compatibles con Hooks. Para verificar la versión que estás utilizando, puedes ejecutar `npm ls react-dom`o`npm ls react-native`en la carpeta de tu aplicación. Si encuentras más de una versión instalada, esto podría causar problemas (más información a continuación).
117
117
118
-
## Duplicate React {/*duplicate-react*/}
118
+
## Uso de más de una instancia de React {/*duplicate-react*/}
119
119
120
-
In order for Hooks to work, the `react`import from your application code needs to resolve to the same module as the `react`import from inside the `react-dom` package.
120
+
Para que los Hooks funcionen correctamente, la importación de `react`en el código de tu aplicación debe apuntar al mismo módulo que la importación de `react`en el paquete `react-dom`.
121
121
122
-
If these `react`imports resolve to two different exports objects, you will see this warning. This may happen if you **accidentally end up with two copies**of the`react` package.
122
+
Si estas importaciones de `react`apuntan a dos objetos de importación diferentes, verás esta advertencia. Esto puede ocurrir si **por error tienes dos copias**del paquete`react`.
123
123
124
-
If you use Node for package management, you can run this check in your project folder:
124
+
Si usas Node para gestionar paquetes, puedes verificar esto en la carpeta de tu proyecto ejecutando:
125
125
126
126
<TerminalBlock>
127
127
128
128
npm ls react
129
129
130
130
</TerminalBlock>
131
131
132
-
If you see more than one React, you'll need to figure out why this happens and fix your dependency tree. For example, maybe a library you're using incorrectly specifies `react`as a dependency (rather than a peer dependency). Until that library is fixed, [Yarn resolutions](https://yarnpkg.com/lang/en/docs/selective-version-resolutions/) is one possible workaround.
132
+
Si detectas más de una instancia de React, tendrás que investigar las causas y corregir tu árbol de dependencias. Es posible que alguna biblioteca que estés utilizando especifique incorrectamente `react`como una dependencia en lugar de una dependencia entre pares. Mientras se soluciona este problema en la biblioteca, una posible solución temporal es utilizar [resoluciones de Yarn](https://runebook.dev/es/docs/yarn/selective-version-resolutions).
133
133
134
-
You can also try to debug this problem by adding some logs and restarting your development server:
134
+
Para solucionar el problema, puedes intentar depurarlo agregando logs y reiniciando el servidor de desarrollo:
135
135
136
136
```js
137
-
//Add this in node_modules/react-dom/index.js
137
+
//Añade esto en node_modules/react-dom/index.js
138
138
window.React1=require('react');
139
139
140
-
//Add this in your component file
140
+
//Añade esto en el archivo de tu componente
141
141
require('react-dom');
142
142
window.React2=require('react');
143
143
console.log(window.React1===window.React2);
144
144
```
145
145
146
-
If it prints `false` then you might have two Reacts and need to figure out why that happened. [This issue](https://github.com/facebook/react/issues/13991)includes some common reasons encountered by the community.
146
+
Si imprime `false`, es posible que tengas dos instancias de React y debas investigar las posibles causas. [Este issue](https://github.com/facebook/react/issues/13991)incluye algunas razones comunes encontradas por la comunidad.
147
147
148
-
This problem can also come up when you use `npm link`or an equivalent. In that case, your bundler might "see" two Reacts — one in application folder and one in your library folder. Assuming`myapp`and`mylib`are sibling folders, one possible fix is to run `npm link ../myapp/node_modules/react`from`mylib`. This should make the library use the application's React copy.
148
+
Este problema también puede surgir al utilizar `npm link`u otro método equivalente, lo que hace que el empaquetador de módulos "vea" dos versiones de React — una en la carpeta de la aplicación y otra en la carpeta de la biblioteca. Si`myapp`y`mylib`son carpetas hermanas, una posible solución es ejecutar `npm link ../myapp/node_modules/react`desde`mylib`. De esta forma, la biblioteca utilizará la versión de React de la aplicación.
149
149
150
150
<Note>
151
151
152
-
In general, React supports using multiple independent copies on one page (for example, if an app and a third-party widget both use it). It only breaks if `require('react')`resolves differently between the component and the `react-dom`copy it was rendered with.
152
+
En general, React permite el uso de varias instancias intependientes en una misma página (por ejemplo, si una aplicación y un widget de terceros lo utilizan). Sin embargo, puede surgir un problema si `require('react')`se resuelve de manera diferente entre el componente y la instancia de `react-dom`utilizada para renderizarlo.
153
153
154
154
</Note>
155
155
156
-
## Other Causes {/*other-causes*/}
156
+
## Otras causas {/*other-causes*/}
157
157
158
-
If none of this worked, please comment in [this issue](https://github.com/facebook/react/issues/13991)and we'll try to help. Try to create a small reproducing example — you might discover the problem as you're doing it.
158
+
Si ninguna de estas soluciones funcionó, por favor coméntalo en [este issue](https://github.com/facebook/react/issues/13991)y trataremos de ayudarte. Intenta crear un pequeño ejemplo que reproduzca el problema — Es posible que descubras la causa del problema mientras intentas reproducirlo.
0 commit comments