diff --git a/src/content/reference/react/use.md b/src/content/reference/react/use.md index 557a71cad..659a6b617 100644 --- a/src/content/reference/react/use.md +++ b/src/content/reference/react/use.md @@ -4,7 +4,7 @@ title: use -`use` is a React API 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` é uma API do React que permite que você leia o valor de um recurso como uma [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) ou um [contexto](/learn/passing-data-deeply-with-context). ```js const value = use(resource); @@ -16,11 +16,11 @@ const value = use(resource); --- -## Reference {/*reference*/} +## Referência {/*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). +Chame `use` em seu componente para ler o valor de um recurso como uma [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) ou [contexto](/learn/passing-data-deeply-with-context). ```jsx import { use } from 'react'; @@ -31,33 +31,33 @@ function MessageComponent({ messagePromise }) { // ... ``` -Unlike React Hooks, `use` can be called within loops and conditional statements like `if`. Like React Hooks, the function that calls `use` must be a Component or Hook. +Ao contrário dos React Hooks, `use` pode ser chamado dentro de loops e instruções condicionais como `if`. Como os React Hooks, a função que chama `use` deve ser um Componente ou Hook. -When called with a Promise, the `use` API 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` API. If the Promise passed to `use` is rejected, the fallback of the nearest Error Boundary will be displayed. +Quando chamado com uma Promise, a API `use` se integra com [`Suspense`](/reference/react/Suspense) e [error boundaries](/reference/react/Component#catching-rendering-errors-with-an-error-boundary). O componente que chama `use` *suspende* enquanto a Promise passada para `use` está pendente. Se o componente que chama `use` for encapsulado em um limite Suspense, o fallback será exibido. Uma vez que a Promise for resolvida, o fallback Suspense é substituído pelos componentes renderizados usando os dados retornados pela API `use`. Se a Promise passada para `use` for rejeitada, o fallback do Error Boundary mais próximo será exibido. -[See more examples below.](#usage) +[Veja mais exemplos abaixo.](#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 é a fonte dos dados de onde você deseja ler um valor. Um recurso pode ser uma [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) ou um [contexto](/learn/passing-data-deeply-with-context). -#### Returns {/*returns*/} +#### Retornos {/*returns*/} -The `use` API 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). +A API `use` retorna o valor que foi lido do recurso, como o valor resolvido de uma [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) ou [contexto](/learn/passing-data-deeply-with-context). -#### Caveats {/*caveats*/} +#### Ressalvas {/*caveats*/} -* The `use` API must be called inside a Component or a Hook. -* When fetching data in a [Server Component](/reference/rsc/server-components), 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/rsc/server-components) and passing them to [Client Components](/reference/rsc/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). +* A API `use` deve ser chamada dentro de um Componente ou um Hook. +* Ao buscar dados em um [Server Component](/reference/rsc/server-components), prefira `async` e `await` em vez de `use`. `async` e `await` retomam a renderização do ponto em que `await` foi invocado, enquanto `use` renderiza novamente o componente após os dados serem resolvidos. +* Prefira criar Promises em [Server Components](/reference/rsc/server-components) e passá-las para [Client Components](/reference/rsc/use-client) em vez de criar Promises em Client Components. Promises criadas em Client Components são recriadas a cada renderização. Promises passadas de um Server Component para um Client Component são estáveis em todas as re-renderizações. [Veja este exemplo](#streaming-data-from-server-to-client). --- -## Usage {/*usage*/} +## Uso {/*usage*/} -### Reading context with `use` {/*reading-context-with-use*/} +### Lendo o contexto com `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. +Quando um [contexto](/learn/passing-data-deeply-with-context) é passado para `use`, ele funciona de forma semelhante a [`useContext`](/reference/react/useContext). Enquanto `useContext` deve ser chamado no nível superior do seu componente, `use` pode ser chamado dentro de condicionais como `if` e loops como `for`. `use` é preferível a `useContext` porque é mais flexível. ```js [[2, 4, "theme"], [1, 4, "ThemeContext"]] import { use } from 'react'; @@ -67,9 +67,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` retorna o valor do contexto para o contexto que você passou. Para determinar o valor do contexto, o React pesquisa na árvore de componentes e encontra **o provider de contexto mais próximo acima** para aquele contexto específico. -To pass context to a `Button`, wrap it or one of its parent components into the corresponding context provider. +Para passar o contexto para um `Button`, envolva-o ou um de seus componentes pai no provider de contexto correspondente. ```js [[1, 3, "ThemeContext"], [2, 3, "\\"dark\\""], [1, 5, "ThemeContext"]] function MyPage() { @@ -85,9 +85,9 @@ function Form() { } ``` -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. +Não importa quantas camadas de componentes existam entre o provider e o `Button`. Quando um `Button` *em qualquer lugar* dentro de `Form` chama `use(ThemeContext)`, ele receberá `"dark"` como o valor. -Unlike [`useContext`](/reference/react/useContext), `use` can be called in conditionals and loops like `if`. +Ao contrário de [`useContext`](/reference/react/useContext), `use` pode ser chamado em condicionais e loops como `if`. ```js [[1, 2, "if"], [2, 3, "use"]] function HorizontalRule({ show }) { @@ -99,11 +99,11 @@ function HorizontalRule({ show }) { } ``` -`use` is called from inside a `if` statement, allowing you to conditionally read values from a Context. +`use` é chamado de dentro de uma instrução `if`, permitindo que você leia condicionalmente valores de um 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)`. +Como `useContext`, `use(context)` sempre procura o provider de contexto mais próximo *acima* do componente que o chama. Ele pesquisa para cima e **não** considera os providers de contexto no componente de onde você está chamando `use(context)`. @@ -194,9 +194,9 @@ function Button({ show, children }) { -### Streaming data from the server to the client {/*streaming-data-from-server-to-client*/} +### Streaming de dados do servidor para o cliente {/*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. +Os dados podem ser transmitidos do servidor para o cliente passando uma Promise como uma prop de um Server Component para um Client Component. ```js [[1, 4, "App"], [2, 2, "Message"], [3, 7, "Suspense"], [4, 8, "messagePromise", 30], [4, 5, "messagePromise"]] import { fetchMessage } from './lib.js'; @@ -212,7 +212,7 @@ export default function App() { } ``` -The Client Component then takes the Promise it received as a prop and passes it to the `use` API. This allows the Client Component to read the value from the Promise that was initially created by the Server Component. +O Client Component então pega a Promise que recebeu como prop e a passa para a API `use`. Isso permite que o Client Component leia o valor da Promise que foi inicialmente criada pelo Server Component. ```js [[2, 6, "Message"], [4, 6, "messagePromise"], [4, 7, "messagePromise"], [5, 7, "use"]] // message.js @@ -225,7 +225,7 @@ export function Message({ messagePromise }) { return

Here is the message: {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` API and the `Message` component will replace the Suspense fallback. +Como o `Message` é encapsulado em [`Suspense`](/reference/react/Suspense), o fallback será exibido até que a Promise seja resolvida. Quando a Promise for resolvida, o valor será lido pela API `use` e o componente `Message` substituirá o fallback Suspense. @@ -294,16 +294,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. +Ao passar uma Promise de um Server Component para um Client Component, seu valor resolvido deve ser serializável para passar entre o servidor e o cliente. Tipos de dados como funções não são serializáveis e não podem ser o valor resolvido de tal Promise. -#### Should I resolve a Promise in a Server or Client Component? {/*resolve-promise-in-server-or-client-component*/} +#### Devo resolver uma Promise em um Server ou Client Component? {/*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` API. You can also resolve the Promise in a Server Component with `await` and pass the required data to the Client Component as a prop. +Uma Promise pode ser passada de um Server Component para um Client Component e resolvida no Client Component com a API `use`. Você também pode resolver a Promise em um Server Component com `await` e passar os dados necessários para o Client Component como uma prop. ```js export default async function App() { @@ -312,24 +312,24 @@ export default async 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. +Mas usar `await` em um [Server Component](/reference/react/components#server-components) bloqueará sua renderização até que a instrução `await` seja finalizada. Passar uma Promise de um Server Component para um Client Component impede que a Promise bloqueie a renderização do Server Component. -### Dealing with rejected Promises {/*dealing-with-rejected-promises*/} +### Lidando com Promises rejeitadas {/*dealing-with-rejected-promises*/} -In some cases a Promise passed to `use` could be rejected. You can handle rejected Promises by either: +Em alguns casos, uma Promise passada para `use` pode ser rejeitada. Você pode lidar com Promises rejeitadas de duas formas: -1. [Displaying an error to users with an 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. [Exibir um erro para os usuários com um error boundary.](#displaying-an-error-to-users-with-error-boundary) +2. [Fornecer um valor alternativo com `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` não pode ser chamado em um bloco try-catch. Em vez de um bloco try-catch [envolva seu componente em um Error Boundary](#displaying-an-error-to-users-with-error-boundary), ou [forneça um valor alternativo para usar com o método `.catch` da Promise](#providing-an-alternative-value-with-promise-catch). -#### Displaying an error to users with an error boundary {/*displaying-an-error-to-users-with-error-boundary*/} +#### Exibindo um erro para os usuários com um error boundary {/*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` API in an error boundary. If the Promise passed to `use` is rejected the fallback for the error boundary will be displayed. +Se você deseja exibir um erro para seus usuários quando uma Promise é rejeitada, pode usar um [error boundary](/reference/react/Component#catching-rendering-errors-with-an-error-boundary). Para usar um error boundary, envolva o componente onde você está chamando a API `use` em um error boundary. Se a Promise passada para `use` for rejeitada, o fallback para o error boundary será exibido. @@ -410,9 +410,9 @@ root.render( ``` -#### Providing an alternative value with `Promise.catch` {/*providing-an-alternative-value-with-promise-catch*/} +#### Fornecendo um valor alternativo com `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. +Se você deseja fornecer um valor alternativo quando a Promise passada para `use` é rejeitada, você pode usar o método [`catch`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch) da Promise. ```js [[1, 6, "catch"],[2, 7, "return"]] import { Message } from './message.js'; @@ -432,31 +432,31 @@ export default function App() { } ``` -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 o método `catch` da Promise, chame `catch` no objeto Promise. `catch` recebe um único argumento: uma função que recebe uma mensagem de erro como um argumento. Qualquer coisa que for retornada pela função passada para `catch` será usada como o valor resolvido da Promise. --- -## Troubleshooting {/*troubleshooting*/} +## Solução de problemas {/*troubleshooting*/} ### "Suspense Exception: This is not a real error!" {/*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). +Você está chamando `use` fora de um Componente ou função Hook do React, ou chamando `use` em um bloco try-catch. Se você estiver chamando `use` dentro de um bloco try-catch, envolva seu componente em um error boundary, ou chame o `catch` da Promise para capturar o erro e resolver a Promise com outro valor. [Veja estes exemplos](#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. +Se você estiver chamando `use` fora de um Componente ou função Hook do React, mova a chamada `use` para um Componente ou função Hook do React. ```jsx function MessageComponent({messagePromise}) { function download() { - // ❌ the function calling `use` is not a Component or Hook + // ❌ a função que chama `use` não é um Componente ou Hook const message = use(messagePromise); // ... ``` -Instead, call `use` outside any component closures, where the function that calls `use` is a Component or Hook. +Em vez disso, chame `use` fora de quaisquer fechamentos de componente, onde a função que chama `use` é um Componente ou Hook. ```jsx function MessageComponent({messagePromise}) { - // ✅ `use` is being called from a component. + // ✅ `use` está sendo chamado de um componente. const message = use(messagePromise); // ... -``` +``` \ No newline at end of file