diff --git a/src/content/reference/react/useDeferredValue.md b/src/content/reference/react/useDeferredValue.md index 6d055f1f9..942d4b7a6 100644 --- a/src/content/reference/react/useDeferredValue.md +++ b/src/content/reference/react/useDeferredValue.md @@ -4,7 +4,7 @@ title: useDeferredValue -`useDeferredValue` is a React Hook that lets you defer updating a part of the UI. +`useDeferredValue` é um Hook do React que permite adiar a atualização de uma parte da interface do usuário. ```js const deferredValue = useDeferredValue(value) @@ -16,11 +16,11 @@ const deferredValue = useDeferredValue(value) --- -## Reference {/*reference*/} +## Referência {/*reference*/} ### `useDeferredValue(value, initialValue?)` {/*usedeferredvalue*/} -Call `useDeferredValue` at the top level of your component to get a deferred version of that value. +Chame `useDeferredValue` no nível mais alto do seu componente para obter uma versão adiada desse valor. ```js import { useState, useDeferredValue } from 'react'; @@ -32,47 +32,47 @@ function SearchPage() { } ``` -[See more examples below.](#usage) +[Veja mais exemplos abaixo.](#usage) -#### Parameters {/*parameters*/} +#### Parâmetros {/*parameters*/} -* `value`: The value you want to defer. It can have any type. -* **optional** `initialValue`: A value to use during the initial render of a component. If this option is omitted, `useDeferredValue` will not defer during the initial render, because there's no previous version of `value` that it can render instead. +* `value`: O valor que você deseja adiar. Ele pode ter qualquer tipo. +* **opcional** `initialValue`: Um valor a ser utilizado durante a renderização inicial de um componente. Se esta opção for omitida, `useDeferredValue` não irá adiar durante a renderização inicial, pois não há uma versão anterior de `value` para renderizar em vez disso. -#### Returns {/*returns*/} +#### Retornos {/*returns*/} -- `currentValue`: During the initial render, the returned deferred value will be the same as the value you provided. During updates, React will first attempt a re-render with the old value (so it will return the old value), and then try another re-render in the background with the new value (so it will return the updated value). +- `currentValue`: Durante a renderização inicial, o valor adiado retornado será o mesmo que o valor fornecido. Durante as atualizações, o React primeiro tentará uma nova renderização com o valor antigo (portanto, retornará o valor antigo) e, em seguida, tentará outra renderização em segundo plano com o novo valor (portanto, retornará o valor atualizado). -In the latest React Canary versions, `useDeferredValue` returns the `initialValue` on initial render, and schedules a re-render in the background with the `value` returned. +Nas versões mais recentes do React Canary, `useDeferredValue` retorna o `initialValue` na renderização inicial e agenda uma nova renderização em segundo plano com o `value` retornado. -#### Caveats {/*caveats*/} +#### Ressalvas {/*caveats*/} -- When an update is inside a Transition, `useDeferredValue` always returns the new `value` and does not spawn a deferred render, since the update is already deferred. +- Quando uma atualização está dentro de uma Transição, `useDeferredValue` sempre retorna o novo `value` e não gera uma renderização adiada, já que a atualização já está adiada. -- The values you pass to `useDeferredValue` should either be primitive values (like strings and numbers) or objects created outside of rendering. If you create a new object during rendering and immediately pass it to `useDeferredValue`, it will be different on every render, causing unnecessary background re-renders. +- Os valores que você passa para `useDeferredValue` devem ser valores primitivos (como strings e números) ou objetos criados fora da renderização. Se você criar um novo objeto durante a renderização e imediatamente passá-lo para `useDeferredValue`, ele será diferente a cada renderização, causando renderizações em segundo plano desnecessárias. -- When `useDeferredValue` receives a different value (compared with [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is)), in addition to the current render (when it still uses the previous value), it schedules a re-render in the background with the new value. The background re-render is interruptible: if there's another update to the `value`, React will restart the background re-render from scratch. For example, if the user is typing into an input faster than a chart receiving its deferred value can re-render, the chart will only re-render after the user stops typing. +- Quando `useDeferredValue` recebe um valor diferente (comparado com [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is)), além da renderização atual (quando ainda usa o valor anterior), ele agenda uma nova renderização em segundo plano com o novo valor. A nova renderização em segundo plano é interrompível: se houver outra atualização para o `value`, o React reiniciará a nova renderização em segundo plano do zero. Por exemplo, se o usuário estiver digitando em um campo de entrada mais rápido do que um gráfico recebendo seu valor adiado pode renderizar, o gráfico só será re-renderizado após o usuário parar de digitar. -- `useDeferredValue` is integrated with [``.](/reference/react/Suspense) If the background update caused by a new value suspends the UI, the user will not see the fallback. They will see the old deferred value until the data loads. +- `useDeferredValue` é integrado com [``](/reference/react/Suspense). Se a atualização em segundo plano causada por um novo valor suspender a interface do usuário, o usuário não verá a opção de recuperação. Eles verão o antigo valor adiado até que os dados sejam carregados. -- `useDeferredValue` does not by itself prevent extra network requests. +- `useDeferredValue` não por si só impede requisições de rede extras. -- There is no fixed delay caused by `useDeferredValue` itself. As soon as React finishes the original re-render, React will immediately start working on the background re-render with the new deferred value. Any updates caused by events (like typing) will interrupt the background re-render and get prioritized over it. +- Não há um atraso fixo causado pelo próprio `useDeferredValue`. Assim que o React termina a renderização original, ele começará imediatamente a trabalhar na nova renderização em segundo plano com o novo valor adiado. Quaisquer atualizações causadas por eventos (como digitação) interromperão a nova renderização em segundo plano e terão prioridade sobre ela. -- The background re-render caused by `useDeferredValue` does not fire Effects until it's committed to the screen. If the background re-render suspends, its Effects will run after the data loads and the UI updates. +- A nova renderização em segundo plano causada por `useDeferredValue` não dispara Efeitos até que esteja comprometida na tela. Se a nova renderização em segundo plano for suspensa, seus Efeitos serão executados após os dados serem carregados e a interface do usuário for atualizada. --- -## Usage {/*usage*/} +## Uso {/*usage*/} -### Showing stale content while fresh content is loading {/*showing-stale-content-while-fresh-content-is-loading*/} +### Mostrando conteúdo defasado enquanto o conteúdo fresco é carregado {/*showing-stale-content-while-fresh-content-is-loading*/} -Call `useDeferredValue` at the top level of your component to defer updating some part of your UI. +Chame `useDeferredValue` no nível mais alto do seu componente para adiar a atualização de alguma parte da sua interface. ```js [[1, 5, "query"], [2, 5, "deferredQuery"]] import { useState, useDeferredValue } from 'react'; @@ -84,26 +84,26 @@ function SearchPage() { } ``` -During the initial render, the deferred value will be the same as the value you provided. +Durante a renderização inicial, o valor adiado será o mesmo que o valor que você forneceu. -During updates, the deferred value will "lag behind" the latest value. In particular, React will first re-render *without* updating the deferred value, and then try to re-render with the newly received value in the background. +Durante as atualizações, o valor adiado irá "atrasar-se" em relação ao valor mais recente. Em particular, o React primeiro re-renderizará *sem* atualizar o valor adiado e, em seguida, tentará re-renderizar com o novo valor recebido em segundo plano. -**Let's walk through an example to see when this is useful.** +**Vamos percorrer um exemplo para ver quando isso é útil.** -This example assumes you use a Suspense-enabled data source: +Este exemplo assume que você usa uma fonte de dados habilitada para Suspense: -- Data fetching with Suspense-enabled frameworks like [Relay](https://relay.dev/docs/guided-tour/rendering/loading-states/) and [Next.js](https://nextjs.org/docs/getting-started/react-essentials) -- Lazy-loading component code with [`lazy`](/reference/react/lazy) -- Reading the value of a Promise with [`use`](/reference/react/use) +- Busca de dados com frameworks habilitados para Suspense, como [Relay](https://relay.dev/docs/guided-tour/rendering/loading-states/) e [Next.js](https://nextjs.org/docs/getting-started/react-essentials) +- Carregamento lento do código do componente com [`lazy`](/reference/react/lazy) +- Lendo o valor de uma Promise com [`use`](/reference/react/use) -[Learn more about Suspense and its limitations.](/reference/react/Suspense) +[Saiba mais sobre Suspense e suas limitações.](/reference/react/Suspense) -In this example, the `SearchResults` component [suspends](/reference/react/Suspense#displaying-a-fallback-while-content-is-loading) while fetching the search results. Try typing `"a"`, waiting for the results, and then editing it to `"ab"`. The results for `"a"` get replaced by the loading fallback. +Neste exemplo, o componente `SearchResults` [suspende](/reference/react/Suspense#displaying-a-fallback-while-content-is-loading) enquanto busca os resultados da pesquisa. Tente digitar `"a"`, aguarde os resultados e então edite para `"ab"`. Os resultados para `"a"` são substituídos pela opção de recuperação de carregamento. @@ -131,10 +131,10 @@ export default function App() { return ( <> - Loading...}> + Carregando...}> @@ -145,11 +145,11 @@ export default function App() { ```js src/SearchResults.js hidden import { fetchData } from './data.js'; -// Note: this component is written using an experimental API -// that's not yet available in stable versions of React. +// Nota: este componente foi escrito usando uma API experimental +// que ainda não está disponível nas versões estáveis do React. -// For a realistic example you can follow today, try a framework -// that's integrated with Suspense, like Relay or Next.js. +// Para um exemplo realista que você pode seguir hoje, tente um framework +// que seja integrado com Suspense, como Relay ou Next.js. export default function SearchResults({ query }) { if (query === '') { @@ -157,7 +157,7 @@ export default function SearchResults({ query }) { } const albums = use(fetchData(`/search?q=${query}`)); if (albums.length === 0) { - return

No matches for "{query}"

; + return

Sem correspondências para "{query}"

; } return (
    @@ -170,8 +170,8 @@ export default function SearchResults({ query }) { ); } -// This is a workaround for a bug to get the demo running. -// TODO: replace with real implementation when the bug is fixed. +// Este é um trabalho em volta de um erro para fazer a demonstração funcionar. +// TODO: substituir por uma implementação real quando o erro for corrigido. function use(promise) { if (promise.status === 'fulfilled') { return promise.value; @@ -197,9 +197,9 @@ function use(promise) { ``` ```js src/data.js hidden -// Note: the way you would do data fetching depends on -// the framework that you use together with Suspense. -// Normally, the caching logic would be inside a framework. +// Nota: a forma como você faria busca de dados depende do +// framework que você usa junto com Suspense. +// Normalmente, a lógica de cache estaria dentro de um framework. let cache = new Map(); @@ -214,12 +214,12 @@ async function getData(url) { if (url.startsWith('/search?q=')) { return await getSearchResults(url.slice('/search?q='.length)); } else { - throw Error('Not implemented'); + throw Error('Não implementado'); } } async function getSearchResults(query) { - // Add a fake delay to make waiting noticeable. + // Adiciona um atraso falso para tornar a espera notável. await new Promise(resolve => { setTimeout(resolve, 500); }); @@ -295,7 +295,7 @@ input { margin: 10px; } -A common alternative UI pattern is to *defer* updating the list of results and to keep showing the previous results until the new results are ready. Call `useDeferredValue` to pass a deferred version of the query down: +Um padrão comum de interface do usuário é *adicionar* a atualização da lista de resultados e continuar mostrando os resultados anteriores até que os novos resultados estejam prontos. Chame `useDeferredValue` para passar uma versão adiada da consulta para baixo: ```js {3,11} export default function App() { @@ -304,10 +304,10 @@ export default function App() { return ( <> - Loading...}> + Carregando...}> @@ -315,9 +315,9 @@ export default function App() { } ``` -The `query` will update immediately, so the input will display the new value. However, the `deferredQuery` will keep its previous value until the data has loaded, so `SearchResults` will show the stale results for a bit. +A `query` será atualizada imediatamente, então o campo de entrada exibirá o novo valor. No entanto, o `deferredQuery` manterá seu valor anterior até que os dados tenham sido carregados, de modo que `SearchResults` mostrará os resultados desatualizados por um tempo. -Enter `"a"` in the example below, wait for the results to load, and then edit the input to `"ab"`. Notice how instead of the Suspense fallback, you now see the stale result list until the new results have loaded: +Digite `"a"` no exemplo abaixo, aguarde o carregamento dos resultados e, em seguida, edite a entrada para `"ab"`. Observe como, ao invés da opção de recuperação do Suspense, você agora vê a lista de resultados desatualizada até que os novos resultados tenham sido carregados: @@ -346,10 +346,10 @@ export default function App() { return ( <> - Loading...}> + Carregando...}> @@ -360,11 +360,11 @@ export default function App() { ```js src/SearchResults.js hidden import { fetchData } from './data.js'; -// Note: this component is written using an experimental API -// that's not yet available in stable versions of React. +// Nota: este componente foi escrito usando uma API experimental +// que ainda não está disponível nas versões estáveis do React. -// For a realistic example you can follow today, try a framework -// that's integrated with Suspense, like Relay or Next.js. +// Para um exemplo realista que você pode seguir hoje, tente um framework +// que é integrado com Suspense, como Relay ou Next.js. export default function SearchResults({ query }) { if (query === '') { @@ -372,7 +372,7 @@ export default function SearchResults({ query }) { } const albums = use(fetchData(`/search?q=${query}`)); if (albums.length === 0) { - return

    No matches for "{query}"

    ; + return

    Sem correspondências para "{query}"

    ; } return (
      @@ -385,8 +385,8 @@ export default function SearchResults({ query }) { ); } -// This is a workaround for a bug to get the demo running. -// TODO: replace with real implementation when the bug is fixed. +// Este é um trabalho em volta de um erro para fazer a demonstração funcionar. +// TODO: substituir por uma implementação real quando o erro for corrigido. function use(promise) { if (promise.status === 'fulfilled') { return promise.value; @@ -412,9 +412,9 @@ function use(promise) { ``` ```js src/data.js hidden -// Note: the way you would do data fetching depends on -// the framework that you use together with Suspense. -// Normally, the caching logic would be inside a framework. +// Nota: a forma como você faria busca de dados depende do +// framework que você usa junto com Suspense. +// Normalmente, a lógica de cache estaria dentro de um framework. let cache = new Map(); @@ -429,12 +429,12 @@ async function getData(url) { if (url.startsWith('/search?q=')) { return await getSearchResults(url.slice('/search?q='.length)); } else { - throw Error('Not implemented'); + throw Error('Não implementado'); } } async function getSearchResults(query) { - // Add a fake delay to make waiting noticeable. + // Adiciona um atraso falso para tornar a espera notável. await new Promise(resolve => { setTimeout(resolve, 500); }); @@ -512,25 +512,25 @@ input { margin: 10px; } -#### How does deferring a value work under the hood? {/*how-does-deferring-a-value-work-under-the-hood*/} +#### Como funciona o adiamento de um valor nos bastidores? {/*how-does-deferring-a-value-work-under-the-hood*/} -You can think of it as happening in two steps: +Você pode pensar que isso acontece em duas etapas: -1. **First, React re-renders with the new `query` (`"ab"`) but with the old `deferredQuery` (still `"a")`.** The `deferredQuery` value, which you pass to the result list, is *deferred:* it "lags behind" the `query` value. +1. **Primeiro, o React re-renderiza com a nova `query` (`"ab"`) mas com o antigo `deferredQuery` (ainda `"a"`).** O valor de `deferredQuery`, que você passa para a lista de resultados, está *adiado:* ele "atrasou-se" em relação ao valor de `query`. -2. **In the background, React tries to re-render with *both* `query` and `deferredQuery` updated to `"ab"`.** If this re-render completes, React will show it on the screen. However, if it suspends (the results for `"ab"` have not loaded yet), React will abandon this rendering attempt, and retry this re-render again after the data has loaded. The user will keep seeing the stale deferred value until the data is ready. +2. **Em segundo plano, o React tenta re-renderizar com *os dois* `query` e `deferredQuery` atualizados para `"ab"`.** Se essa nova renderização for concluída, o React a mostrará na tela. No entanto, se ela suspender (os resultados para `"ab"` ainda não foram carregados), o React abandonará essa tentativa de renderização e tentará mais uma vez após os dados terem sido carregados. O usuário continuará vendo o valor adiado desatualizado até que os dados estejam prontos. -The deferred "background" rendering is interruptible. For example, if you type into the input again, React will abandon it and restart with the new value. React will always use the latest provided value. +A renderização "em segundo plano" adiada é interrompível. Por exemplo, se você digitar no campo de entrada novamente, o React abandonará essa renderização e reiniciará com o novo valor. O React sempre usará o valor mais recente fornecido. -Note that there is still a network request per each keystroke. What's being deferred here is displaying results (until they're ready), not the network requests themselves. Even if the user continues typing, responses for each keystroke get cached, so pressing Backspace is instant and doesn't fetch again. +Observe que ainda existe uma requisição de rede para cada tecla digitada. O que está sendo adiado aqui é a exibição de resultados (até que estejam prontos), não as requisições de rede em si. Mesmo se o usuário continuar digitando, as respostas para cada tecla digitada são armazenadas em cache, então pressionar Backspace é instantâneo e não busca novamente. --- -### Indicating that the content is stale {/*indicating-that-the-content-is-stale*/} +### Indicando que o conteúdo está desatualizado {/*indicating-that-the-content-is-stale*/} -In the example above, there is no indication that the result list for the latest query is still loading. This can be confusing to the user if the new results take a while to load. To make it more obvious to the user that the result list does not match the latest query, you can add a visual indication when the stale result list is displayed: +No exemplo acima, não há indicação de que a lista de resultados para a consulta mais recente ainda está carregando. Isso pode ser confuso para o usuário se os novos resultados demorarem a carregar. Para deixar mais óbvio para o usuário que a lista de resultados não corresponde à consulta mais recente, você pode adicionar uma indicação visual quando a lista de resultados desatualizada é exibida: ```js {2}
      ``` -With this change, as soon as you start typing, the stale result list gets slightly dimmed until the new result list loads. You can also add a CSS transition to delay dimming so that it feels gradual, like in the example below: +Com essa mudança, assim que você começar a digitar, a lista de resultados desatualizada será ligeiramente diminuída até que a nova lista de resultados carregue. Você também pode adicionar uma transição CSS para atrasar a diminuição de modo que se sinta gradual, como no exemplo abaixo: @@ -570,10 +570,10 @@ export default function App() { return ( <> - Loading...}> + Carregando...}>