diff --git a/src/content/reference/react/use.md b/src/content/reference/react/use.md index bb2fb6d5d..36487edf6 100644 --- a/src/content/reference/react/use.md +++ b/src/content/reference/react/use.md @@ -5,13 +5,13 @@ canary: true -The `use` 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 `use` 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). -`use` is a React Hook that lets you read the value of a resource like a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) or [context](/learn/passing-data-deeply-with-context). +`use` es un Hook de React que te permite leer el valor de un recurso como una [Promesa](https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Promise) o [contexto](/learn/passing-data-deeply-with-context). ```js const value = use(resource); @@ -23,11 +23,11 @@ const value = use(resource); --- -## Reference {/*reference*/} +## Referencia {/*reference*/} ### `use(resource)` {/*use*/} -Call `use` in your component to read the value of a resource like a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) or [context](/learn/passing-data-deeply-with-context). +Llama a `use` en tu componente para leer el valor de un recurso como una [Promesa](https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Promise) o [contexto](/learn/passing-data-deeply-with-context). ```jsx import { use } from 'react'; @@ -38,33 +38,33 @@ function MessageComponent({ messagePromise }) { // ... ``` -Unlike all other React Hooks, `use` can be called within loops and conditional statements like `if`. Like other React Hooks, the function that calls `use` must be a Component or Hook. +A diferencia de otros Hooks de React, `use` puede ser llamado dentro de bucles y condicionales como `if`. Al igual que otros Hooks de React, la función que llama a `use` tiene que ser un componente o Hook. -When called with a Promise, the `use` Hook integrates with [`Suspense`](/reference/react/Suspense) and [error boundaries](/reference/react/Component#catching-rendering-errors-with-an-error-boundary). The component calling `use` *suspends* while the Promise passed to `use` is pending. If the component that calls `use` is wrapped in a Suspense boundary, the fallback will be displayed. Once the Promise is resolved, the Suspense fallback is replaced by the rendered components using the data returned by the `use` Hook. If the Promise passed to `use` is rejected, the fallback of the nearest Error Boundary will be displayed. +Cuando es llamado con una Promesa, el Hook de `use` se integra con [`Suspense`](/reference/react/Suspense) y [barreras de error](/reference/react/Component#catching-rendering-errors-with-an-error-boundary). El componente que llama a `use` *se suspende* mientras que la Promesa pasada a `use` es pendiente. Si el componente que llama a `use` es envuelto en una barrera de Suspense, el fallback será mostrado. Una vez que la Promesa es resuelta, el fallback de Suspense es remplazada por los componentes renderizados usando los datos devueltos por el Hook `use`. Si la Promesa pasada a `use` es rechazada, se mostrará el fallback del error mas cercano a la barrera de error. -[See more examples below.](#usage) +[Ver más ejemplos abajo.](#usage) -#### Parameters {/*parameters*/} +#### Parámetros {/*parameters*/} -* `resource`: this is the source of the data you want to read a value from. A resource can be a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) or a [context](/learn/passing-data-deeply-with-context). +* `resource`: esta es la fuente de los datos de los que quieres leer un valor. Un recurso puede ser una [Promesa](https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Promise) o un [contexto](/learn/passing-data-deeply-with-context). -#### Returns {/*returns*/} +#### Devuelve {/*returns*/} -The `use` Hook returns the value that was read from the resource like the resolved value of a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) or [context](/learn/passing-data-deeply-with-context). +El Hook `use` devuelve el valor que se leyó del recurso como el valor resuelto de una [Promesa](https://developer.mozilla.org/es/docs/Web/JavaScript/Reference/Global_Objects/Promise) o [contexto](/learn/passing-data-deeply-with-context). -#### Caveats {/*caveats*/} +#### Advertencias {/*caveats*/} -* The `use` Hook must be called inside a Component or a Hook. -* When fetching data in a [Server Component](/reference/react/use-server), prefer `async` and `await` over `use`. `async` and `await` pick up rendering from the point where `await` was invoked, whereas `use` re-renders the component after the data is resolved. -* Prefer creating Promises in [Server Components](/reference/react/use-server) and passing them to [Client Components](/reference/react/use-client) over creating Promises in Client Components. Promises created in Client Components are recreated on every render. Promises passed from a Server Component to a Client Component are stable across re-renders. [See this example](#streaming-data-from-server-to-client). +* El Hook `use` debe ser llamado dentro de un componente o un Hook. +* Cuando se recupera datos en un [Componente del Servidor](/reference/react/use-server), se prefiere el uso de `async` y `await` por encima de `use`. `async` y `await` retoman el renderizado desde el punto donde se invocó `await`, mientras que `use` vuelve a renderizar el componente después de que se resuelvan los datos. +* Se prefiere la creación de Promesas en los [Componente del Servidors](/reference/react/use-server) y pasarlos a los [Componente del Clientes](/reference/react/use-client) por encima de crear Promesas en los Componente del Clientes. Las Promesas creadas en los Componente del Clientes son recreadas en cada renderizado. Las Promesas que son pasadas de un Componente del Servidor a un Componente del Cliente son estables en todos los renderizados. [Ver este ejemplo](#streaming-data-from-server-to-client). --- -## Usage {/*usage*/} +## Uso {/*usage*/} -### Reading context with `use` {/*reading-context-with-use*/} +### Leer contexto con `use` {/*reading-context-with-use*/} -When a [context](/learn/passing-data-deeply-with-context) is passed to `use`, it works similarly to [`useContext`](/reference/react/useContext). While `useContext` must be called at the top level of your component, `use` can be called inside conditionals like `if` and loops like `for`. `use` is preferred over `useContext` because it is more flexible. +Cuando un [contexto](/learn/passing-data-deeply-with-context) se pasa a `use`, funciona de manera similar a [`useContext`](/reference/react/useContext). Mientras `useContext` debe ser llamado en el nivel mas alto de tu componente, `use` puede ser llamado dentro de condicionales como `if` y en bucles como `for`. Se prefiere `use` por encima de `useContext` porque es más flexible. ```js [[2, 4, "theme"], [1, 4, "ThemeContext"]] import { use } from 'react'; @@ -74,9 +74,9 @@ function Button() { // ... ``` -`use` returns the context value for the context you passed. To determine the context value, React searches the component tree and finds **the closest context provider above** for that particular context. +`use` devuelve el valor de contexto para el contexto que pasas. Para determinar el valor del contexto, React busca en el árbol de componentes y encuentra **el proveedor de contexto más cercano arriba** para ese contexto en particular. -To pass context to a `Button`, wrap it or one of its parent components into the corresponding context provider. +Para pasar el contexto a un `Button`, envuélvalo en uno de sus componentes padres en el proveedor de contexto correspondiente. ```js [[1, 3, "ThemeContext"], [2, 3, "\\"dark\\""], [1, 5, "ThemeContext"]] function MyPage() { @@ -88,13 +88,13 @@ function MyPage() { } function Form() { - // ... renders buttons inside ... + // ... renderiza botones adentro ... } ``` -It doesn't matter how many layers of components there are between the provider and the `Button`. When a `Button` *anywhere* inside of `Form` calls `use(ThemeContext)`, it will receive `"dark"` as the value. +No importa cuántas capas de componentes hay entre el proveedor y el `Button`. Cuando un `Button` *en cualquier lugar* dentro de un `Form` llama a `use(ThemeContext)`, recibirá `"dark"` como valor. -Unlike [`useContext`](/reference/react/useContext), `use` can be called in conditionals and loops like `if`. +A diferencia de [`useContext`](/reference/react/useContext), `use` se puede llamar en condicionales y bucles como `if`. ```js [[1, 2, "if"], [2, 3, "use"]] function HorizontalRule({ show }) { @@ -106,11 +106,11 @@ function HorizontalRule({ show }) { } ``` -`use` is called from inside a `if` statement, allowing you to conditionally read values from a Context. +`use` se llama desde dentro de una declaración `if`, lo que te permite leer valores condicionalmente de un contexto. -Like `useContext`, `use(context)` always looks for the closest context provider *above* the component that calls it. It searches upwards and **does not** consider context providers in the component from which you're calling `use(context)`. +Al igual que `useContext`, `use(context)` siempre busca el proveedor de contexto más cercano *arriba* del componente que lo llama. Busca hacia arriba y no considera los proveedores de contexto en el componente desde el cual llamas `use(context)`. @@ -131,9 +131,9 @@ export default function MyApp() { function Form() { return ( - - - + + + ); } @@ -212,9 +212,9 @@ function Button({ show, children }) { -### Streaming data from the server to the client {/*streaming-data-from-server-to-client*/} +### Transmisión de datos del servidor al cliente (streaming) {/*streaming-data-from-server-to-client*/} -Data can be streamed from the server to the client by passing a Promise as a prop from a Server Component to a Client Component. +Se puede transmitir un flujo de datos del servidor al cliente (*streaming*) pasando una Promesa como una prop desde un Componente del Servidor a un Componente del Cliente. ```js [[1, 4, "App"], [2, 2, "Message"], [3, 7, "Suspense"], [4, 8, "messagePromise", 30], [4, 5, "messagePromise"]] import { fetchMessage } from './lib.js'; @@ -223,14 +223,14 @@ import { Message } from './message.js'; export default function App() { const messagePromise = fetchMessage(); return ( - waiting for message...

}> + Esperando mensaje...

}>
); } ``` -The Client Component then takes the Promise it received as a prop and passes it to the `use` Hook. This allows the Client Component to read the value from the Promise that was initially created by the Server Component. +El Componente del Cliente toma la Promesa que ha recibido como una prop y la pasa al Hook `use`. Esto permite al Componente del Cliente leer el valor de la Promesa que fue inicialmente creada por el Componente del Servidor. ```js [[2, 6, "Message"], [4, 6, "messagePromise"], [4, 7, "messagePromise"], [5, 7, "use"]] // message.js @@ -240,10 +240,10 @@ import { use } from 'react'; export function Message({ messagePromise }) { const messageContent = use(messagePromise); - return

Here is the message: {messageContent}

; + return

Aquí está el mensaje: {messageContent}

; } ``` -Because `Message` is wrapped in [`Suspense`](/reference/react/Suspense), the fallback will be displayed until the Promise is resolved. When the Promise is resolved, the value will be read by the `use` Hook and the `Message` component will replace the Suspense fallback. +Debido a que `Message` está envuelto en [`Suspense`](/reference/react/Suspense), el fallback se mostrará hasta que la Promesa esté resuelta. Cuando se resuelva la Promesa, el valor será leído por el Hook `use` y el componente `Message` reemplazará el fallback de Suspense. @@ -254,12 +254,12 @@ import { use, Suspense } from "react"; function Message({ messagePromise }) { const messageContent = use(messagePromise); - return

Here is the message: {messageContent}

; + return

Aquí está el mensaje: {messageContent}

; } export function MessageContainer({ messagePromise }) { return ( - ⌛Downloading message...

}> + ⌛Descargando mensaje...

}>
); @@ -285,7 +285,7 @@ export default function App() { if (show) { return ; } else { - return ; + return ; } } ``` @@ -325,16 +325,16 @@ root.render( -When passing a Promise from a Server Component to a Client Component, its resolved value must be serializable to pass between server and client. Data types like functions aren't serializable and cannot be the resolved value of such a Promise. +Al pasar una Promesa de un Componente del Servidor a un Componente del Cliente, su valor resuelto debe ser serializable para pasar entre el servidor y el cliente. Los tipos de datos como las funciones no son serializables y no pueden ser el valor resuelto de dicha Promesa. -#### Should I resolve a Promise in a Server or Client Component? {/*resolve-promise-in-server-or-client-component*/} +#### ¿Debo resolver una promesa en un Componente del Servidor o en un Componente del Cliente? {/*resolve-promise-in-server-or-client-component*/} -A Promise can be passed from a Server Component to a Client Component and resolved in the Client Component with the `use` Hook. You can also resolve the Promise in a Server Component with `await` and pass the required data to the Client Component as a prop. +Una Promesa se puede pasar de un Componente del Servidor a un Componente del Cliente y resolverse en el Componente del Cliente con el Hook `use`. También puedes resolver la Promesa en un Componente del Servidor con `await` y pasar los datos requeridos al Componente del Cliente como una prop. ```js export default function App() { @@ -343,24 +343,24 @@ export default function App() { } ``` -But using `await` in a [Server Component](/reference/react/components#server-components) will block its rendering until the `await` statement is finished. Passing a Promise from a Server Component to a Client Component prevents the Promise from blocking the rendering of the Server Component. +Pero el uso de `await` en un [Componente del Servidor](/reference/react/components#server-components) bloqueará su renderizado hasta que finalice la declaración de `await`. Pasar una Promesa de un Componente del Servidor a un Componente del Cliente evita que la Promesa bloquee la representación del Componente del Servidor. -### Dealing with rejected Promises {/*dealing-with-rejected-promises*/} +### Lidiar con las promesas rechazadas {/*dealing-with-rejected-promises*/} -In some cases a Promise passed to `use` could be rejected. You can handle rejected Promises by either: +En algunas ocasiones una Promesa pasada a `use` puede ser rechazada. Puedes manejar Promesas rechazadas de estas maneras: -1. [Displaying an error to users with error boundary.](#displaying-an-error-to-users-with-error-boundary) -2. [Providing an alternative value with `Promise.catch`](#providing-an-alternative-value-with-promise-catch) +1. [Mostrar un error a los usuarios con una barrera de error.](#displaying-an-error-to-users-with-error-boundary) +2. [Proporcionar un valor alternativo con `Promise.catch`](#providing-an-alternative-value-with-promise-catch) -`use` cannot be called in a try-catch block. Instead of a try-catch block [wrap your component in an Error Boundary](#displaying-an-error-to-users-with-error-boundary), or [provide an alternative value to use with the Promise's `.catch` method](#providing-an-alternative-value-with-promise-catch). +`use` no puede ser llamado en un bloque try-catch. En vez de un bloque try-catch [envuelve tu componente con una barrera de error](#displaying-an-error-to-users-with-error-boundary), o [proporciona un valor alternativo para usar con el método `.catch` de Promise](#providing-an-alternative-value-with-promise-catch). -#### Displaying an error to users with a error boundary {/*displaying-an-error-to-users-with-error-boundary*/} +#### Mostrar un error a los usuarios con una barrera de error {/*displaying-an-error-to-users-with-error-boundary*/} -If you'd like to display an error to your users when a Promise is rejected, you can use an [error boundary](/reference/react/Component#catching-rendering-errors-with-an-error-boundary). To use an error boundary, wrap the component where you are calling the `use` Hook in an error boundary. If the Promise passed to `use` is rejected the fallback for the error boundary will be displayed. +Si quieres mostrar un error a tus usuarios cuando se rechaza una Promesa, puedes usar una [barrera de error](/reference/react/Component#catching-rendering-errors-with-an-error-boundary). Para usar una barrera de error, envuelve el componente donde estás llamando al Hook `use` en una barrera de error. Si se rechaza la Promesa que fue pasada a `use`, se mostrará el fallback para la barrera de error. @@ -372,8 +372,8 @@ import { ErrorBoundary } from "react-error-boundary"; export function MessageContainer({ messagePromise }) { return ( - ⚠️Something went wrong

}> - ⌛Downloading message...

}> + ⚠️Algo ha salido mal

}> + ⌛Descargando el mensaje...

}>
@@ -382,7 +382,7 @@ export function MessageContainer({ messagePromise }) { function Message({ messagePromise }) { const content = use(messagePromise); - return

Here is the message: {content}

; + return

Aquí está el mensaje: {content}

; } ``` @@ -405,7 +405,7 @@ export default function App() { if (show) { return ; } else { - return ; + return ; } } ``` @@ -444,9 +444,9 @@ root.render( ```
-#### Providing an alternative value with `Promise.catch` {/*providing-an-alternative-value-with-promise-catch*/} +#### Proporcionar un valor alternativo con `Promise.catch` {/*providing-an-alternative-value-with-promise-catch*/} -If you'd like to provide an alternative value when the Promise passed to `use` is rejected you can use the Promise's [`catch`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch) method. +Si quieres proporcionar un valor alternativo cuando se rechaza la Promesa pasada a `use`, puedes usar el método [`catch`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch) de la Promesa. ```js [[1, 6, "catch"],[2, 7, "return"]] import { Message } from './message.js'; @@ -455,42 +455,42 @@ export default function App() { const messagePromise = new Promise((resolve, reject) => { reject(); }).catch(() => { - return "no new message found."; + return "no se encontró ningún mensaje nuevo."; }); return ( - waiting for message...

}> + Esperando mensaje...

}>
); } ``` -To use the Promise's `catch` method, call `catch` on the Promise object. `catch` takes a single argument: a function that takes an error message as an argument. Whatever is returned by the function passed to `catch` will be used as the resolved value of the Promise. +Para usar el método `catch` de la Promesa, llama a `catch` en el objeto de la Promesa. `catch` toma un solo argumento: una función que toma un mensaje de error como un argumento. Lo que sea devuelto por la función pasada a `catch` se utilizará como valor resuelto de la Promesa. --- -## Troubleshooting {/*troubleshooting*/} +## Solución de problemas {/*troubleshooting*/} -### "Suspense Exception: This is not a real error!" {/*suspense-exception-error*/} +### “Excepción de Suspense: ¡Esto no es un error real!” {/*suspense-exception-error*/} -You are either calling `use` outside of a React component or Hook function, or calling `use` in a try–catch block. If you are calling `use` inside a try–catch block, wrap your component in an error boundary, or call the Promise's `catch` to catch the error and resolve the Promise with another value. [See these examples](#dealing-with-rejected-promises). +Estás llamando a `use` fuera de un componente de React o función Hook, o llamando a `use` en un bloque try-catch. Si estás llamando a `use` dentro de un bloque try-catch, envuelve tu componente en una barrera de error o llama al `catch` de la Promesa para detectar el error y resolver la Promesa con otro valor. [Ver estos ejemplos](#dealing-with-rejected-promises). -If you are calling `use` outside a React component or Hook function, move the `use` call to a React component or Hook function. +Si estás llamando a `use` fuera de un componente de React o función Hook, mueve la llamada de `use` a un componente de React o función Hook. ```jsx function MessageComponent({messagePromise}) { function download() { - // ❌ the function calling `use` is not a Component or Hook + // ❌ la función que llama a `use` no es un componente ni un Hook const message = use(messagePromise); // ... ``` -Instead, call `use` outside any component closures, where the function that calls `use` is a component or Hook. +En su lugar, llama a `use` fuera de las clausuras de cualquier componente, donde la función que llama a `use` es un componente o un Hook. ```jsx function MessageComponent({messagePromise}) { - // ✅ `use` is being called from a component. + // ✅ `use` está siendo llamado desde un componente. const message = use(messagePromise); // ... ```