diff --git a/src/content/reference/react-dom/hooks/useFormStatus.md b/src/content/reference/react-dom/hooks/useFormStatus.md index 70feceaea..e6841cb4e 100644 --- a/src/content/reference/react-dom/hooks/useFormStatus.md +++ b/src/content/reference/react-dom/hooks/useFormStatus.md @@ -5,13 +5,13 @@ canary: true -The `useFormStatus` Hook is currently only available in React's Canary and experimental channels. Learn more about [React's release channels here](/community/versioning-policy#all-release-channels). +El Hook `useFormStatus` está actualmente disponible solo en React Canary y canales experimentales. Aprende más sobre los [canales de lanzamiento de React aquí](/community/versioning-policy#all-release-channels). -`useFormStatus` is a Hook that gives you status information of the last form submission. +`useFormStatus` es un Hook que brinda información de estado del último formulario enviado. ```js const { pending, data, method, action } = useFormStatus(); @@ -23,11 +23,11 @@ const { pending, data, method, action } = useFormStatus(); --- -## Reference {/*reference*/} +## Referencia {/*reference*/} ### `useFormStatus()` {/*use-form-status*/} -The `useFormStatus` Hook provides status information of the last form submission. +El Hook `useFormStatus` provee información de estado del último formulario enviado. ```js {5},[[1, 6, "status.pending"]] import { useFormStatus } from "react-dom"; @@ -35,7 +35,7 @@ import action from './actions'; function Submit() { const status = useFormStatus(); - return + return } export default function App() { @@ -47,42 +47,42 @@ export default function App() { } ``` -To get status information, the `Submit` component must be rendered within a `
`. The Hook returns information like the `pending` property which tells you if the form is actively submitting. +Para obtener información de estado, el componente de `Enviar` tiene que ser renderizado dentro de un ``. El Hook retorna información como la propiedad `pending` que te dice si el formulario se está enviando activamente. -In the above example, `Submit` uses this information to disable ` ); } @@ -133,30 +133,30 @@ export async function submitForm(query) { -##### `useFormStatus` will not return status information for a `` rendered in the same component. {/*useformstatus-will-not-return-status-information-for-a-form-rendered-in-the-same-component*/} +##### `useFormStatus` no retorna información de estado a un `` renderizado en el mismo componente. {/*useformstatus-will-not-return-status-information-for-a-form-rendered-in-the-same-component*/} -The `useFormStatus` Hook only returns status information for a parent `` and not for any `` rendered in the same component calling the Hook, or child components. +El Hook `useFormStatus` solo retorna información de estado a un `` padre y no para ningún `` renderizado en el mismo componente que llama el Hook, o componentes hijos. ```js function Form() { - // 🚩 `pending` will never be true - // useFormStatus does not track the form rendered in this component + // 🚩 `pending` nunca será true + // useFormStatus no rastrea el formulario renderizado en este componente const { pending } = useFormStatus(); return ; } ``` -Instead call `useFormStatus` from inside a component that is located inside `
`. +En su lugar llama a `useFormStatus` desde dentro de un componente que se encuentra dentro de un ``. ```js function Submit() { - // ✅ `pending` will be derived from the form that wraps the Submit component + // ✅ `pending` se derivará del formulario que envuelve el componente Enviar const { pending } = useFormStatus(); return ; } function Form() { - // This is the `useFormStatus` tracks + // Este es el que `useFormStatus` rastrea return ( @@ -167,11 +167,11 @@ function Form() { -### Read the form data being submitted {/*read-form-data-being-submitted*/} +### Lee los datos del formulario que se envían {/*read-form-data-being-submitted*/} -You can use the `data` property of the status information returned from `useFormStatus` to display what data is being submitted by the user. +Puedes usar la propiedad `data` de la información de estado que retorna del `useFormStatus` para mostrar qué datos está siendo enviando por el usuario. -Here, we have a form where users can request a username. We can use `useFormStatus` to display a temporary status message confirming what username they have requested. +Aquí, tenemos un formulario donde los usuarios pueden solicitar un nombre de usuario. Podemos usar `useFormStatus` para mostrar temporalmente un mensaje de estado que confirme qué nombre de usuario han solicitado. @@ -184,13 +184,13 @@ export default function UsernameForm() { return (
-

Request a Username:

+

Solicita un nombre de usuario:


-

{data ? `Requesting ${data?.get("username")}...`: ''}

+

{data ? `Solicitando ${data?.get("username")}...`: ''}

); } @@ -249,12 +249,12 @@ button { --- -## Troubleshooting {/*troubleshooting*/} +## Solución de problemas {/*troubleshooting*/} -### `status.pending` is never `true` {/*pending-is-never-true*/} +### `status.pending` nunca es `true` {/*pending-is-never-true*/} -`useFormStatus` will only return status information for a parent ``. +`useFormStatus` solo retornará información de estado a un `` padre. -If the component that calls `useFormStatus` is not nested in a ``, `status.pending` will always return `false`. Verify `useFormStatus` is called in a component that is a child of a `` element. +Si el componente que llama a `useFormStatus` no está anidado en un ``, `status.pending` siempre retornará `false`. Verifica que `useFormStatus` está siendo llamado en un componente que es hijo de un elemento ``. -`useFormStatus` will not track the status of a `` rendered in the same component. See [Pitfall](#useformstatus-will-not-return-status-information-for-a-form-rendered-in-the-same-component) for more details. +`useFormStatus` no rastreará al estado de un `` renderizado en el mismo componente. Mira [Atención](#useformstatus-will-not-return-status-information-for-a-form-rendered-in-the-same-component) para más detalles. diff --git a/src/content/reference/react/experimental_taintObjectReference.md b/src/content/reference/react/experimental_taintObjectReference.md index b5b9e513d..096a83fea 100644 --- a/src/content/reference/react/experimental_taintObjectReference.md +++ b/src/content/reference/react/experimental_taintObjectReference.md @@ -4,30 +4,30 @@ title: experimental_taintObjectReference -**This API is experimental and is not available in a stable version of React yet.** +**Esta API es experimental y aún no está disponible en una versión estable de React.** -You can try it by upgrading React packages to the most recent experimental version: +Puedes probarla actualizando los paquetes de React a la versión experimental más reciente: - `react@experimental` - `react-dom@experimental` - `eslint-plugin-react-hooks@experimental` -Experimental versions of React may contain bugs. Don't use them in production. +Las versiones experimentales de React pueden contener errores. No las uses en producción. -This API is only available inside React Server Components. +Esta API únicamente está disponible dentro de Componentes de Servidor en React -`taintObjectReference` lets you prevent a specific object instance from being passed to a Client Component like a `user` object. +`taintObjectReference` te permite evitar que una instancia específica de objeto sea pasada a un Componente Cliente, como un objecto `user`. ```js experimental_taintObjectReference(message, object); ``` -To prevent passing a key, hash or token, see [`taintUniqueValue`](/reference/react/experimental_taintUniqueValue). +Para prevenir el pasar una llave, hash o token, ver [`taintUniqueValue`](/reference/react/experimental_taintUniqueValue). @@ -35,11 +35,11 @@ To prevent passing a key, hash or token, see [`taintUniqueValue`](/reference/rea --- -## Reference {/*reference*/} +## Referencia {/*reference*/} ### `taintObjectReference(message, object)` {/*taintobjectreference*/} -Call `taintObjectReference` with an object to register it with React as something that should not be allowed to be passed to the Client as is: +Llama a `taintObjectReference` con un objeto para registrarlo en React como algo que no debería permitirse pasar al Cliente tal cual: ```js import {experimental_taintObjectReference} from 'react'; @@ -50,35 +50,35 @@ experimental_taintObjectReference( ); ``` -[See more examples below.](#usage) +[Ver más ejemplos abajo.](#usage) -#### Parameters {/*parameters*/} +#### Parámetros {/*parameters*/} -* `message`: The message you want to display if the object gets passed to a Client Component. This message will be displayed as a part of the Error that will be thrown if the object gets passed to a Client Component. +* `message`: El mensaje que deseas mostrar si el objeto se pasa a un Componente Cliente. Este mensaje se mostrará como parte del Error que se lanzará si el objeto se pasa a un Componente Cliente. -* `object`: The object to be tainted. Functions and class instances can be passed to `taintObjectReference` as `object`. Functions and classes are already blocked from being passed to Client Components but the React's default error message will be replaced by what you defined in `message`. When a specific instance of a Typed Array is passed to `taintObjectReference` as `object`, any other copies of the Typed Array will not be tainted. +* `object`: El objeto a contaminar. Funciones e instancias de clases pueden ser pasadas a `taintObjectReference` como `object`. Las funciones y clases ya están bloqueadas para ser pasadas a Componentes Cliente, pero el mensaje de error predeterminado de React será reemplazado por lo que hayas definido en el `message`. Cuando una instancia específica de una matriz tipada se pasa a `taintObjectReference` como `object`, cualquier otra copia de la matriz tipada no será contaminada. -#### Returns {/*returns*/} +#### Devuelve {/*returns*/} -`experimental_taintObjectReference` returns `undefined`. +`experimental_taintObjectReference` devuelve `undefined`. #### Caveats {/*caveats*/} -- Recreating or cloning a tainted object creates a new untainted object which may contain sensitive data. For example, if you have a tainted `user` object, `const userInfo = {name: user.name, ssn: user.ssn}` or `{...user}` will create new objects which are not tainted. `taintObjectReference` only protects against simple mistakes when the object is passed through to a Client Component unchanged. +- Recrear o clonar un objeto contaminado crea un nuevo objeto no contaminado que puede contener datos sensibles. Por ejemplo, si tienes un objeto `user` contaminado, `const userInfo = {name: user.name, ssn: user.ssn}` o `{...user}` creará nuevos objetos que no estarán contamidos. `taintObjectReference` solo protege contra errores simples cuando el objeto se pasa sin cambios a un Componente Cliente. -**Do not rely on just tainting for security.** Tainting an object doesn't prevent leaking of every possible derived value. For example, the clone of a tainted object will create a new untainted object. Using data from a tainted object (e.g. `{secret: taintedObj.secret}`) will create a new value or object that is not tainted. Tainting is a layer of protection; a secure app will have multiple layers of protection, well designed APIs, and isolation patterns. +**No confíes únicamente en la 'contaminación' para la seguridad.** Contaminar un objeto no evita la filtración de todos los valores derivados posibles. Por ejemplo, el clon de un objeto contaminado creará un nuevo objeto no contaminado. Usar datos de un objeto contaminado (e.j. `{secret: taintedObj.secret}`) creará un nuevo valor u objeto que no esté contaminado. La contaminación es una capa de protección; una aplicación segura tendrá múltiples capas de protección, APIs bien diseñadas y patrones de aislamiento. --- -## Usage {/*usage*/} +## Uso {/*usage*/} -### Prevent user data from unintentionally reaching the client {/*prevent-user-data-from-unintentionally-reaching-the-client*/} +### Evita que los datos de usuario lleguen al cliente de manera no intencionada {/*prevent-user-data-from-unintentionally-reaching-the-client*/} -A Client Component should never accept objects that carry sensitive data. Ideally, the data fetching functions should not expose data that the current user should not have access to. Sometimes mistakes happen during refactoring. To protect against these mistakes happening down the line we can "taint" the user object in our data API. +Un Componente Cliente nunca debería aceptar objetos que contengan datos sensibles. Idealmente, las funciones de obtención de datos no deberían exponer datos a los que el usuario actual no debería tener acceso. A veces, ocurren errores durante la refactorización. Para protegernos contra estos errores en el futuro, podemos 'contaminar' el objeto de usuario en nuestra API de datos. ```js import {experimental_taintObjectReference} from 'react'; @@ -94,13 +94,13 @@ export async function getUser(id) { } ``` -Now whenever anyone tries to pass this object to a Client Component, an error will be thrown with the passed in error message instead. +Ahora, cada vez que alguien intente pasar este objeto a un Componente Cliente, se lanzará un error con el mensaje de error proporcionado. -#### Protecting against leaks in data fetching {/*protecting-against-leaks-in-data-fetching*/} +#### Protegiendo contra fugas en la obtención de datos. {/*protecting-against-leaks-in-data-fetching*/} -If you're running a Server Components environment that has access to sensitive data, you have to be careful not to pass objects straight through: +Si estás ejecutando un entorno de Componentes de Servidor que tiene acceso a datos sensibles, debes tener cuidado de no pasar objetos directamente: ```js // api.js @@ -130,7 +130,7 @@ export async function InfoCard({ user }) { } ``` -Ideally, the `getUser` should not expose data that the current user should not have access to. To prevent passing the `user` object to a Client Component down the line we can "taint" the user object: +Idealmente, la función `getUser` no debería exponer datos a los que el `user` actual no debería tener acceso. Para evitar pasar el objeto de usuario a un Componente Cliente más adelante, podemos "contaminar" el objeto de usuario: ```js @@ -148,6 +148,6 @@ export async function getUser(id) { } ``` -Now if anyone tries to pass the `user` object to a Client Component, an error will be thrown with the passed in error message. +Ahora, si alguien intenta pasar el objeto de `user` a un Componente Cliente, se lanzará un error con el mensaje de error proporcionado. diff --git a/src/content/reference/react/hooks.md b/src/content/reference/react/hooks.md index 6dea3a0fd..4da1cef44 100644 --- a/src/content/reference/react/hooks.md +++ b/src/content/reference/react/hooks.md @@ -1,23 +1,23 @@ --- -title: "Built-in React Hooks" +title: "Hooks integrados en React " --- -*Hooks* let you use different React features from your components. You can either use the built-in Hooks or combine them to build your own. This page lists all built-in Hooks in React. +Los *Hooks* te dejan usar diferentes características de React de sus componentes. Puedes también usar los Hooks integrados o combinarlos para crear el tuyo. Esta página enumera todos los Hooks integrados en React. --- -## State Hooks {/*state-hooks*/} +## Hooks de estado {/*state-hooks*/} -*State* lets a component ["remember" information like user input.](/learn/state-a-components-memory) For example, a form component can use state to store the input value, while an image gallery component can use state to store the selected image index. +El *Estado* permite a un componente ["recordar" información como el input del usuario.](/learn/state-a-components-memory) Por ejemplo, un componente de formulario puede usar el estado para almacenar el valor de entrada, mientras que un componente de galería de imágenes puede usar el estado para almacenar el indicé de la imagen seleccionada. -To add state to a component, use one of these Hooks: +Para añadir un estado a un componente, usa de estos Hooks: -* [`useState`](/reference/react/useState) declares a state variable that you can update directly. -* [`useReducer`](/reference/react/useReducer) declares a state variable with the update logic inside a [reducer function.](/learn/extracting-state-logic-into-a-reducer) +* [`useState`](/reference/react/useState) declara un estado variable que puedes actualizar directamente. +* [`useReducer`](/reference/react/useReducer) declara un estado variable con la lógica de actualización dentro de una [función reductora.](/learn/extracting-state-logic-into-a-reducer) ```js function ImageGallery() { @@ -27,11 +27,11 @@ function ImageGallery() { --- -## Context Hooks {/*context-hooks*/} +## Hooks de Contexto {/*context-hooks*/} -*Context* lets a component [receive information from distant parents without passing it as props.](/learn/passing-props-to-a-component) For example, your app's top-level component can pass the current UI theme to all components below, no matter how deep. +El *Contexto* permite a un componente [recibir información desde un componente padre distante sin pasarsela como props.](/learn/passing-props-to-a-component) Por ejemplo, tu componente en el nivel más alto de tu aplicación puede pasar el tema de interfaz de usuario actual a todos los componentes debajo, no importa que tan profundo estén. -* [`useContext`](/reference/react/useContext) reads and subscribes to a context. +* [`useContext`](/reference/react/useContext) lee y se suscribe a un Contexto. ```js function Button() { @@ -41,12 +41,12 @@ function Button() { --- -## Ref Hooks {/*ref-hooks*/} +## Hooks Ref {/*ref-hooks*/} -*Refs* let a component [hold some information that isn't used for rendering,](/learn/referencing-values-with-refs) like a DOM node or a timeout ID. Unlike with state, updating a ref does not re-render your component. Refs are an "escape hatch" from the React paradigm. They are useful when you need to work with non-React systems, such as the built-in browser APIs. +Los *Refs* permiten a un componente [conserva algo de información que no es usada para el renderizado,](/learn/referencing-values-with-refs) como un nodo del DOM or el ID de un timeout. A diferencia del estado, actualizar un ref no no vuelve a renderizar tu componente. Los refs son una "puerta de escape" del paradigma de React. Son útiles cuando necesitas trabajar con sistemas que no son de React, como son las APIs integradas del navegador. -* [`useRef`](/reference/react/useRef) declares a ref. You can hold any value in it, but most often it's used to hold a DOM node. -* [`useImperativeHandle`](/reference/react/useImperativeHandle) lets you customize the ref exposed by your component. This is rarely used. +* [`useRef`](/reference/react/useRef) declara un ref. Puedes conservar cualquier valor en él, pero más frecuentemente se utiliza para conservar un node del DOM. +* [`useImperativeHandle`](/reference/react/useImperativeHandle) te permite personalizar el ref expuesto por tu componente. Es raramente utilizado. ```js function Form() { @@ -56,11 +56,11 @@ function Form() { --- -## Effect Hooks {/*effect-hooks*/} +## Hooks de Efecto {/*effect-hooks*/} -*Effects* let a component [connect to and synchronize with external systems.](/learn/synchronizing-with-effects) This includes dealing with network, browser DOM, animations, widgets written using a different UI library, and other non-React code. +Los *Efectos* permiten a un componente [conectarse y sincronizarse con sistemas externos.](/learn/synchronizing-with-effects) Esto incluye lidiar con la red, el DOM del navegador, animaciones, widgets escritos usando una biblioteca UI distinta, y otro código que no sea de React. -* [`useEffect`](/reference/react/useEffect) connects a component to an external system. +* [`useEffect`](/reference/react/useEffect) conecta un componente a un sistema externo. ```js function ChatRoom({ roomId }) { @@ -72,23 +72,23 @@ function ChatRoom({ roomId }) { // ... ``` -Effects are an "escape hatch" from the React paradigm. Don't use Effects to orchestrate the data flow of your application. If you're not interacting with an external system, [you might not need an Effect.](/learn/you-might-not-need-an-effect) +Los Efectos son una "puerta de escape" del paradigma de React. No utilices los Efectos para orquestar el flujo de los datos de tu aplicación. Si no estas interactuando con un sistema externo, [puede que no necesites un Efecto.](/learn/you-might-not-need-an-effect) -There are two rarely used variations of `useEffect` with differences in timing: +Hay dos variaciones raramente usadas de `useEffect` con diferencias en la sincronización: -* [`useLayoutEffect`](/reference/react/useLayoutEffect) fires before the browser repaints the screen. You can measure layout here. -* [`useInsertionEffect`](/reference/react/useInsertionEffect) fires before React makes changes to the DOM. Libraries can insert dynamic CSS here. +* [`useLayoutEffect`](/reference/react/useLayoutEffect) se activa antes de que el navegador vuelve a pintar la pantalla. Puedes medir la maquetación aquí. +* [`useInsertionEffect`](/reference/react/useInsertionEffect) se activa antes de que React realice cambios al DOM. Las bibliotecas pueden insertar CSS dinámico aquí. --- -## Performance Hooks {/*performance-hooks*/} +## Hooks de rendimiento {/*performance-hooks*/} -A common way to optimize re-rendering performance is to skip unnecessary work. For example, you can tell React to reuse a cached calculation or to skip a re-render if the data has not changed since the previous render. +Una forma común de optimizar el rendimiento del re-renderizado es saltarse el trabajo innecesario. Por ejemplo, puedes decirle a React que reutilice cálculos que están en la cache o que se salte un re-renderizado si los datos no han cambiado desde el renderizado anterior. -To skip calculations and unnecessary re-rendering, use one of these Hooks: +Para saltarse cálculos y re-renderizados innecesarios, usa uno de estos Hooks: -- [`useMemo`](/reference/react/useMemo) lets you cache the result of an expensive calculation. -- [`useCallback`](/reference/react/useCallback) lets you cache a function definition before passing it down to an optimized component. +- [`useMemo`](/reference/react/useMemo) te permite almacenar en caché el resultado de un cálculo costoso. +- [`useCallback`](/reference/react/useCallback) te permite almacenar en caché la definición de una función antes de pasarla a un componente optimizado. ```js function TodoList({ todos, tab, theme }) { @@ -97,26 +97,26 @@ function TodoList({ todos, tab, theme }) { } ``` -Sometimes, you can't skip re-rendering because the screen actually needs to update. In that case, you can improve performance by separating blocking updates that must be synchronous (like typing into an input) from non-blocking updates which don't need to block the user interface (like updating a chart). +A veces, no podrás saltarte re-renderizados porque la pantalla realmente necesita actualizarse. En ese caso, puede mejorar el rendimiento separando actualizaciones bloqueantes que deben ser síncronas (como escribir en un input) desde actualizaciones no bloqueantes las cuales no necesitan bloquear la interfaz de usuario (como actualizar una gráfica). -To prioritize rendering, use one of these Hooks: +Para priorizar el renderizado, usa uno de estos Hooks: -- [`useTransition`](/reference/react/useTransition) lets you mark a state transition as non-blocking and allow other updates to interrupt it. -- [`useDeferredValue`](/reference/react/useDeferredValue) lets you defer updating a non-critical part of the UI and let other parts update first. +- [`useTransition`](/reference/react/useTransition) te permite marcar un estado de transición como no bloqueante y permite a otras actualizaciones interrumpirlo. +- [`useDeferredValue`](/reference/react/useDeferredValue) te permite aplazar la actualización de una parte no critica de la UI y permite a las otras partes actualizarse primero. --- -## Other Hooks {/*other-hooks*/} +## Otros Hooks {/*other-hooks*/} -These Hooks are mostly useful to library authors and aren't commonly used in the application code. +Estos Hooks son mayormente útiles para los autores de bibliotecas y no son comúnmente utilizados para el código de una aplicación. -- [`useDebugValue`](/reference/react/useDebugValue) lets you customize the label React DevTools displays for your custom Hook. -- [`useId`](/reference/react/useId) lets a component associate a unique ID with itself. Typically used with accessibility APIs. -- [`useSyncExternalStore`](/reference/react/useSyncExternalStore) lets a component subscribe to an external store. +- [`useDebugValue`](/reference/react/useDebugValue) te permite personalizar la etiqueta que las herramientas de desarrollo de muestran para tu Hook personalizado. +- [`useId`](/reference/react/useId) permite a un componente se asocie a sí mismo un identificador único. Típicamente es usado con APIs de accesibilidad. +- [`useSyncExternalStore`](/reference/react/useSyncExternalStore) permite a un componente suscribirse a una store externo. * [`useActionState`](/reference/react/useActionState) allows you to manage state of actions. --- -## Your own Hooks {/*your-own-hooks*/} +## Tus propios Hooks {/*your-own-hooks*/} -You can also [define your own custom Hooks](/learn/reusing-logic-with-custom-hooks#extracting-your-own-custom-hook-from-a-component) as JavaScript functions. +Puedes también [definir tus propios Hooks personalizados](/learn/reusing-logic-with-custom-hooks#extracting-your-own-custom-hook-from-a-component) como funciones de JavaScript. diff --git a/src/content/reference/react/lazy.md b/src/content/reference/react/lazy.md index e49dd409a..ff6378925 100644 --- a/src/content/reference/react/lazy.md +++ b/src/content/reference/react/lazy.md @@ -202,7 +202,7 @@ En cambio, decláralos siempre en el nivel superior de tu módulo: ```js {3-4} import { lazy } from 'react'; -// ✅ Good: Declare lazy components outside of your components +// ✅ Bien: Declarar componentes lazy fuera de tus componentes const MarkdownPreview = lazy(() => import('./MarkdownPreview.js')); function Editor() { diff --git a/src/content/reference/rules/rules-of-hooks.md b/src/content/reference/rules/rules-of-hooks.md index ecaef7c60..6cf925039 100644 --- a/src/content/reference/rules/rules-of-hooks.md +++ b/src/content/reference/rules/rules-of-hooks.md @@ -1,53 +1,53 @@ --- -title: Rules of Hooks +title: Reglas de los Hooks --- -Hooks are defined using JavaScript functions, but they represent a special type of reusable UI logic with restrictions on where they can be called. +Los Hooks se definen mediante funciones JavaScript. Representan un tipo especial de lógica de UI reutilizable, con ciertas restricciones acerca de dónde pueden ser llamados. --- -## Only call Hooks at the top level {/*only-call-hooks-at-the-top-level*/} +## Sólo llama a los Hooks en el nivel más alto {/*only-call-hooks-at-the-top-level*/} -Functions whose names start with `use` are called [*Hooks*](/reference/react) in React. +En React, las funciones cuyos nombres empiezan con `use` son llamadas [*Hooks*](/reference/react). -**Don’t call Hooks inside loops, conditions, nested functions, or `try`/`catch`/`finally` blocks.** 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: +**No llames a los Hooks dentro de bucles, condicionales, funciones anidadas o bloques `try`/`catch`/`finally`.** En su lugar, utilízalos siempre en el nivel más alto de tu función React, antes de cualquier retorno anticipado. Sólo puedes llamar a los Hooks mientras React esté renderizando un componente funcional: -* ✅ Call them at the top level in the body of a [function component](/learn/your-first-component). -* ✅ Call them at the top level in the body of a [custom Hook](/learn/reusing-logic-with-custom-hooks). +* ✅ Llámalos en el nivel más alto del cuerpo de un [componente funcional](/learn/your-first-component). +* ✅ Llámalos en el nivel más alto del cuerpo de un [custom Hook](/learn/reusing-logic-with-custom-hooks). ```js{2-3,8-9} function Counter() { - // ✅ Good: top-level in a function component + // ✅ Bien: nivel más alto en un componente funcional const [count, setCount] = useState(0); // ... } function useWindowWidth() { - // ✅ Good: top-level in a custom Hook + // ✅ Bien: nivel más alto en un custom Hook const [width, setWidth] = useState(window.innerWidth); // ... } ``` -It’s **not** supported to call Hooks (functions starting with `use`) in any other cases, for example: +No se admite llamar a los Hooks (funciones que empiezan con `use`) en casos como por ejemplo: -* 🔴 Do not call Hooks inside conditions or loops. -* 🔴 Do not call Hooks after a conditional `return` statement. -* 🔴 Do not call Hooks in event handlers. -* 🔴 Do not call Hooks in class components. -* 🔴 Do not call Hooks inside functions passed to `useMemo`, `useReducer`, or `useEffect`. -* 🔴 Do not call Hooks inside `try`/`catch`/`finally` blocks. +* 🔴 No llamar a los Hooks dentro de condicionales o bucles. +* 🔴 No llamar a los Hooks después de una declaración `return` condicional. +* 🔴 No llamar a los Hooks dentro de event handlers. +* 🔴 No llamar a los Hooks dentro de componentes de clase. +* 🔴 No llamar a los Hooks dentro de funciones pasadas a `useMemo`, `useReducer` o `useEffect`. +* 🔴 No llamar a los Hooks dentro de bloques `try`/`catch`/`finally`. -If you break these rules, you might see this error. +Si rompes estas reglas, es posible que veas este error. ```js{3-4,11-12,20-21} function Bad({ cond }) { if (cond) { - // 🔴 Bad: inside a condition (to fix, move it outside!) + // 🔴 Mal: Hook llamado dentro de una condición (solución, muévelo afuera de la condición!) const theme = useContext(ThemeContext); } // ... @@ -55,7 +55,7 @@ function Bad({ cond }) { function Bad() { for (let i = 0; i < 10; i++) { - // 🔴 Bad: inside a loop (to fix, move it outside!) + // 🔴 Mal: Hook llamado dentro de un bucle (solución, muévelo afuera del bucle!) const theme = useContext(ThemeContext); } // ... @@ -65,14 +65,14 @@ function Bad({ cond }) { if (cond) { return; } - // 🔴 Bad: after a conditional return (to fix, move it before the return!) + // 🔴 Mal: Hook llamado después de una condición de retorno (solución, muévelo antes del return!) const theme = useContext(ThemeContext); // ... } function Bad() { function handleClick() { - // 🔴 Bad: inside an event handler (to fix, move it outside!) + // 🔴 Mal: Hook llamado dentro de una función event handler (solución, muévelo afuera de la función event handler!) const theme = useContext(ThemeContext); } // ... @@ -80,7 +80,7 @@ function Bad() { function Bad() { const style = useMemo(() => { - // 🔴 Bad: inside useMemo (to fix, move it outside!) + // 🔴 Mal: Hook llamado dentro de un useMemo (solución, muévelo afuera de la función useMemo!) const theme = useContext(ThemeContext); return createStyle(theme); }); @@ -89,7 +89,7 @@ function Bad() { class Bad extends React.Component { render() { - // 🔴 Bad: inside a class component (to fix, write a function component instead of a class!) + // 🔴 Mal: Hook llamado dentro de un componente de clase (solución, escribe un componente funcional en vez de un componente de clase!) useEffect(() => {}) // ... } @@ -97,7 +97,7 @@ class Bad extends React.Component { function Bad() { try { - // 🔴 Bad: inside try/catch/finally block (to fix, move it outside!) + // 🔴 Bad: Hook llamado dentro de un bloque try/catch/finally (solución, muévelo afuera del bloque!) const [x, setX] = useState(0); } catch { const [x, setX] = useState(1); @@ -105,31 +105,31 @@ function Bad() { } ``` -You can use the [`eslint-plugin-react-hooks` plugin](https://www.npmjs.com/package/eslint-plugin-react-hooks) to catch these mistakes. +Puedes usar el [`eslint-plugin-react-hooks` plugin](https://www.npmjs.com/package/eslint-plugin-react-hooks), para capturar estos errores. -[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. +Es *posible* que los [Custom Hooks](/learn/reusing-logic-with-custom-hooks) llamen a otros Hooks (ése es su propósito). Esto funciona porque se supone que los custom Hooks sean también llamados, sólo mientras se renderiza un componente funcional. --- -## Only call Hooks from React functions {/*only-call-hooks-from-react-functions*/} +## Sólo llama a los Hooks desde funciones React {/*only-call-hooks-from-react-functions*/} -Don’t call Hooks from regular JavaScript functions. Instead, you can: +No llames a los Hooks desde funciones convencionales de JavaScript. En su lugar, puedes: -✅ Call Hooks from React function components. -✅ Call Hooks from [custom Hooks](/learn/reusing-logic-with-custom-hooks#extracting-your-own-custom-hook-from-a-component). +✅ Llamar a los Hooks desde componentes funcionales de React. +✅ Llamar a los Hooks desde otros [custom Hooks](/learn/reusing-logic-with-custom-hooks#extracting-your-own-custom-hook-from-a-component). -By following this rule, you ensure that all stateful logic in a component is clearly visible from its source code. +Al seguir esta regla, nos aseguramos que toda la lógica del estado de un componente, sea claramente visible desde su código fuente. ```js {2,5} function FriendList() { const [onlineStatus, setOnlineStatus] = useOnlineStatus(); // ✅ } -function setOnlineStatus() { // ❌ Not a component or custom Hook! +function setOnlineStatus() { // ❌ No es ni un componente ni un custom Hook! const [onlineStatus, setOnlineStatus] = useOnlineStatus(); } ```