diff --git a/src/content/reference/react-dom/client/hydrateRoot.md b/src/content/reference/react-dom/client/hydrateRoot.md index b74e2c38e..9c83f1683 100644 --- a/src/content/reference/react-dom/client/hydrateRoot.md +++ b/src/content/reference/react-dom/client/hydrateRoot.md @@ -1,10 +1,9 @@ --- title: hydrateRoot --- - -`hydrateRoot` lets you display React components inside a browser DOM node whose HTML content was previously generated by [`react-dom/server`.](/reference/react-dom/server) +`hydrateRoot` permite que você exiba componentes React dentro de um nó DOM do navegador cujo conteúdo HTML foi gerado anteriormente por [`react-dom/server`.](/reference/react-dom/server) ```js const root = hydrateRoot(domNode, reactNode, options?) @@ -16,11 +15,11 @@ const root = hydrateRoot(domNode, reactNode, options?) --- -## Reference {/*reference*/} +## Referência {/*reference*/} ### `hydrateRoot(domNode, reactNode, options?)` {/*hydrateroot*/} -Call `hydrateRoot` to “attach” React to existing HTML that was already rendered by React in a server environment. +Chame `hydrateRoot` para "anexar" o React a um HTML existente que já foi renderizado pelo React em um ambiente de servidor. ```js import { hydrateRoot } from 'react-dom/client'; @@ -29,101 +28,101 @@ const domNode = document.getElementById('root'); const root = hydrateRoot(domNode, reactNode); ``` -React will attach to the HTML that exists inside the `domNode`, and take over managing the DOM inside it. An app fully built with React will usually only have one `hydrateRoot` call with its root component. +O React se anexará ao HTML que existe dentro do `domNode` e assumirá o gerenciamento do DOM dentro dele. Um aplicativo totalmente construído com React geralmente terá apenas uma chamada `hydrateRoot` com seu componente raiz. -[See more examples below.](#usage) +[Veja mais exemplos abaixo.](#usage) -#### Parameters {/*parameters*/} +#### Parâmetros {/*parameters*/} -* `domNode`: A [DOM element](https://developer.mozilla.org/en-US/docs/Web/API/Element) that was rendered as the root element on the server. +* `domNode`: Um [elemento DOM](https://developer.mozilla.org/en-US/docs/Web/API/Element) que foi renderizado como o elemento raiz no servidor. -* `reactNode`: The "React node" used to render the existing HTML. This will usually be a piece of JSX like `` which was rendered with a `ReactDOM Server` method such as `renderToPipeableStream()`. +* `reactNode`: O "nó React" usado para renderizar o HTML existente. Geralmente será um trecho de JSX como ``, que foi renderizado com um método do `ReactDOM Server`, como `renderToPipeableStream()`. -* **optional** `options`: An object with options for this React root. +* **opcional** `options`: Um objeto com opções para esta raiz React. - * **optional** `onCaughtError`: Callback called when React catches an error in an Error Boundary. Called with the `error` caught by the Error Boundary, and an `errorInfo` object containing the `componentStack`. - * **optional** `onUncaughtError`: Callback called when an error is thrown and not caught by an Error Boundary. Called with the `error` that was thrown and an `errorInfo` object containing the `componentStack`. - * **optional** `onRecoverableError`: Callback called when React automatically recovers from errors. Called with the `error` React throws, and an `errorInfo` object containing the `componentStack`. Some recoverable errors may include the original error cause as `error.cause`. - * **optional** `identifierPrefix`: A string prefix React uses for IDs generated by [`useId`.](/reference/react/useId) Useful to avoid conflicts when using multiple roots on the same page. Must be the same prefix as used on the server. + * **opcional** `onCaughtError`: Callback chamado quando o React captura um erro em um Error Boundary. Chamado com o `error` capturado pelo Error Boundary e um objeto `errorInfo` contendo o `componentStack`. + * **opcional** `onUncaughtError`: Callback chamado quando um erro é lançado e não é capturado por um Error Boundary. Chamado com o `error` que foi lançado e um objeto `errorInfo` contendo o `componentStack`. + * **opcional** `onRecoverableError`: Callback chamado quando o React se recupera automaticamente de erros. Chamado com o `error` que o React lança e um objeto `errorInfo` contendo o `componentStack`. Alguns erros recuperáveis podem incluir a causa original do erro como `error.cause`. + * **opcional** `identifierPrefix`: Um prefixo de string que o React usa para IDs gerados por [`useId`.](/reference/react/useId) Útil para evitar conflitos ao usar várias raízes na mesma página. Deve ser o mesmo prefixo usado no servidor. -#### Returns {/*returns*/} +#### Retorna {/*returns*/} -`hydrateRoot` returns an object with two methods: [`render`](#root-render) and [`unmount`.](#root-unmount) +`hydrateRoot` retorna um objeto com dois métodos: [`render`](#root-render) e [`unmount`.](#root-unmount) -#### Caveats {/*caveats*/} +#### Ressalvas {/*caveats*/} -* `hydrateRoot()` expects the rendered content to be identical with the server-rendered content. You should treat mismatches as bugs and fix them. -* In development mode, React warns about mismatches during hydration. There are no guarantees that attribute differences will be patched up in case of mismatches. This is important for performance reasons because in most apps, mismatches are rare, and so validating all markup would be prohibitively expensive. -* You'll likely have only one `hydrateRoot` call in your app. If you use a framework, it might do this call for you. -* If your app is client-rendered with no HTML rendered already, using `hydrateRoot()` is not supported. Use [`createRoot()`](/reference/react-dom/client/createRoot) instead. +* `hydrateRoot()` espera que o conteúdo renderizado seja idêntico ao conteúdo renderizado pelo servidor. Você deve tratar as incompatibilidades como bugs e corrigi-las. +* No modo de desenvolvimento, o React avisa sobre incompatibilidades durante a hidratação. Não há garantias de que as diferenças de atributos serão corrigidas em caso de incompatibilidades. Isso é importante por razões de desempenho, pois na maioria dos aplicativos, as incompatibilidades são raras, e validar toda a marcação seria proibitivamente caro. +* Você provavelmente terá apenas uma chamada `hydrateRoot` em seu aplicativo. Se você usar um framework, ele pode fazer essa chamada para você. +* Se o seu aplicativo for renderizado no cliente sem nenhum HTML já renderizado, usar `hydrateRoot()` não é suportado. Use [`createRoot()`](/reference/react-dom/client/createRoot) em vez disso. --- ### `root.render(reactNode)` {/*root-render*/} -Call `root.render` to update a React component inside a hydrated React root for a browser DOM element. +Chame `root.render` para atualizar um componente React dentro de uma raiz React hidratada para um elemento DOM do navegador. ```js root.render(); ``` -React will update `` in the hydrated `root`. +O React atualizará `` na `root` hidratada. -[See more examples below.](#usage) +[Veja mais exemplos abaixo.](#usage) -#### Parameters {/*root-render-parameters*/} +#### Parâmetros {/*root-render-parameters*/} -* `reactNode`: A "React node" that you want to update. This will usually be a piece of JSX like ``, but you can also pass a React element constructed with [`createElement()`](/reference/react/createElement), a string, a number, `null`, or `undefined`. +* `reactNode`: Um "nó React" que você deseja atualizar. Geralmente será um trecho de JSX como ``, mas você também pode passar um elemento React construído com [`createElement()`](/reference/react/createElement), uma string, um número, `null` ou `undefined`. -#### Returns {/*root-render-returns*/} +#### Retorna {/*root-render-returns*/} -`root.render` returns `undefined`. +`root.render` retorna `undefined`. -#### Caveats {/*root-render-caveats*/} +#### Ressalvas {/*root-render-caveats*/} -* If you call `root.render` before the root has finished hydrating, React will clear the existing server-rendered HTML content and switch the entire root to client rendering. +* Se você chamar `root.render` antes que a raiz termine de hidratar, o React limpará o conteúdo HTML existente renderizado pelo servidor e mudará toda a raiz para a renderização do cliente. --- ### `root.unmount()` {/*root-unmount*/} -Call `root.unmount` to destroy a rendered tree inside a React root. +Chame `root.unmount` para destruir uma árvore renderizada dentro de uma raiz React. ```js root.unmount(); ``` -An app fully built with React will usually not have any calls to `root.unmount`. +Um aplicativo totalmente construído com React geralmente não terá nenhuma chamada para `root.unmount`. -This is mostly useful if your React root's DOM node (or any of its ancestors) may get removed from the DOM by some other code. For example, imagine a jQuery tab panel that removes inactive tabs from the DOM. If a tab gets removed, everything inside it (including the React roots inside) would get removed from the DOM as well. You need to tell React to "stop" managing the removed root's content by calling `root.unmount`. Otherwise, the components inside the removed root won't clean up and free up resources like subscriptions. +Isso é útil principalmente se o nó DOM da raiz React (ou qualquer um de seus ancestrais) puder ser removido do DOM por algum outro código. Por exemplo, imagine um painel de abas do jQuery que remove abas inativas do DOM. Se uma aba for removida, tudo dentro dela (incluindo as raízes React) também seria removido do DOM. Você precisa dizer ao React para "parar" de gerenciar o conteúdo da raiz removida chamando `root.unmount`. Caso contrário, os componentes dentro da raiz removida não farão a limpeza e liberarão recursos como assinaturas. -Calling `root.unmount` will unmount all the components in the root and "detach" React from the root DOM node, including removing any event handlers or state in the tree. +Chamar `root.unmount` desmontará todos os componentes na raiz e "desanexará" o React do nó DOM raiz, incluindo a remoção de quaisquer manipuladores de eventos ou estado na árvore. -#### Parameters {/*root-unmount-parameters*/} +#### Parâmetros {/*root-unmount-parameters*/} -`root.unmount` does not accept any parameters. +`root.unmount` não aceita nenhum parâmetro. -#### Returns {/*root-unmount-returns*/} +#### Retorna {/*root-unmount-returns*/} -`root.unmount` returns `undefined`. +`root.unmount` retorna `undefined`. -#### Caveats {/*root-unmount-caveats*/} +#### Ressalvas {/*root-unmount-caveats*/} -* Calling `root.unmount` will unmount all the components in the tree and "detach" React from the root DOM node. +* Chamar `root.unmount` desmontará todos os componentes na árvore e "desanexará" o React do nó DOM raiz. -* Once you call `root.unmount` you cannot call `root.render` again on the root. Attempting to call `root.render` on an unmounted root will throw a "Cannot update an unmounted root" error. +* Depois de chamar `root.unmount`, você não poderá mais chamar `root.render` na raiz. Tentar chamar `root.render` em uma raiz desmontada lançará um erro "Cannot update an unmounted root". --- -## Usage {/*usage*/} +## Uso {/*usage*/} -### Hydrating server-rendered HTML {/*hydrating-server-rendered-html*/} +### Hidratando HTML renderizado pelo servidor {/*hydrating-server-rendered-html*/} -If your app's HTML was generated by [`react-dom/server`](/reference/react-dom/client/createRoot), you need to *hydrate* it on the client. +Se o HTML do seu aplicativo foi gerado por [`react-dom/server`](/reference/react-dom/client/createRoot), você precisa *hidratá-lo* no cliente. ```js [[1, 3, "document.getElementById('root')"], [2, 3, ""]] import { hydrateRoot } from 'react-dom/client'; @@ -131,16 +130,16 @@ import { hydrateRoot } from 'react-dom/client'; hydrateRoot(document.getElementById('root'), ); ``` -This will hydrate the server HTML inside the browser DOM node with the React component for your app. Usually, you will do it once at startup. If you use a framework, it might do this behind the scenes for you. +Isso hidratará o HTML do servidor dentro do nó DOM do navegador com o componente React do seu aplicativo. Geralmente, você fará isso uma vez na inicialização. Se você usar um framework, ele pode fazer isso nos bastidores para você. -To hydrate your app, React will "attach" your components' logic to the initial generated HTML from the server. Hydration turns the initial HTML snapshot from the server into a fully interactive app that runs in the browser. +Para hidratar seu aplicativo, o React "anexará" a lógica dos seus componentes ao HTML inicial gerado pelo servidor. A hidratação transforma o snapshot HTML inicial do servidor em um aplicativo totalmente interativo que é executado no navegador. ```html public/index.html

Hello, world!

``` @@ -180,30 +179,30 @@ function Counter() {
-You shouldn't need to call `hydrateRoot` again or to call it in more places. From this point on, React will be managing the DOM of your application. To update the UI, your components will [use state](/reference/react/useState) instead. +Você não deve precisar chamar `hydrateRoot` novamente ou chamá-lo em mais lugares. A partir deste ponto, o React gerenciará o DOM do seu aplicativo. Para atualizar a interface do usuário, seus componentes usarão [estado](/reference/react/useState) em vez disso. -The React tree you pass to `hydrateRoot` needs to produce **the same output** as it did on the server. +A árvore React que você passa para `hydrateRoot` precisa produzir **a mesma saída** que produziu no servidor. -This is important for the user experience. The user will spend some time looking at the server-generated HTML before your JavaScript code loads. Server rendering creates an illusion that the app loads faster by showing the HTML snapshot of its output. Suddenly showing different content breaks that illusion. This is why the server render output must match the initial render output on the client. +Isso é importante para a experiência do usuário. O usuário passará algum tempo olhando para o HTML gerado pelo servidor antes que seu código JavaScript seja carregado. A renderização do servidor cria uma ilusão de que o aplicativo carrega mais rápido mostrando o snapshot HTML de sua saída. Mostrar repentinamente conteúdo diferente quebra essa ilusão. É por isso que a saída da renderização do servidor deve corresponder à saída da renderização inicial no cliente. -The most common causes leading to hydration errors include: +As causas mais comuns que levam a erros de hidratação incluem: -* Extra whitespace (like newlines) around the React-generated HTML inside the root node. -* Using checks like `typeof window !== 'undefined'` in your rendering logic. -* Using browser-only APIs like [`window.matchMedia`](https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia) in your rendering logic. -* Rendering different data on the server and the client. +* Espaços em branco extras (como novas linhas) em torno do HTML gerado pelo React dentro do nó raiz. +* Usando verificações como `typeof window !== 'undefined'` em sua lógica de renderização. +* Usando APIs exclusivas do navegador como [`window.matchMedia`](https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia) em sua lógica de renderização. +* Renderizando dados diferentes no servidor e no cliente. -React recovers from some hydration errors, but **you must fix them like other bugs.** In the best case, they'll lead to a slowdown; in the worst case, event handlers can get attached to the wrong elements. +O React se recupera de alguns erros de hidratação, mas **você deve corrigi-los como outros bugs.** Na melhor das hipóteses, eles levarão a uma lentidão; na pior das hipóteses, os manipuladores de eventos podem ser anexados aos elementos errados. --- -### Hydrating an entire document {/*hydrating-an-entire-document*/} +### Hidratando um documento inteiro {/*hydrating-an-entire-document*/} -Apps fully built with React can render the entire document as JSX, including the [``](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/html) tag: +Aplicativos totalmente construídos com React podem renderizar o documento inteiro como JSX, incluindo a tag [``](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/html): ```js {3,13} function App() { @@ -223,7 +222,7 @@ function App() { } ``` -To hydrate the entire document, pass the [`document`](https://developer.mozilla.org/en-US/docs/Web/API/Window/document) global as the first argument to `hydrateRoot`: +Para hidratar o documento inteiro, passe o global [`document`](https://developer.mozilla.org/en-US/docs/Web/API/Window/document) como o primeiro argumento para `hydrateRoot`: ```js {4} import { hydrateRoot } from 'react-dom/client'; @@ -234,18 +233,18 @@ hydrateRoot(document, ); --- -### Suppressing unavoidable hydration mismatch errors {/*suppressing-unavoidable-hydration-mismatch-errors*/} +### Suprimindo erros de incompatibilidade de hidratação inevitáveis {/*suppressing-unavoidable-hydration-mismatch-errors*/} -If a single element’s attribute or text content is unavoidably different between the server and the client (for example, a timestamp), you may silence the hydration mismatch warning. +Se o atributo ou conteúdo de texto de um único elemento for inegavelmente diferente entre o servidor e o cliente (por exemplo, um timestamp), você pode silenciar o aviso de incompatibilidade de hidratação. -To silence hydration warnings on an element, add `suppressHydrationWarning={true}`: +Para silenciar avisos de hidratação em um elemento, adicione `suppressHydrationWarning={true}`: ```html public/index.html

Current Date: 01/01/2020

``` @@ -270,20 +269,20 @@ export default function App() {
-This only works one level deep, and is intended to be an escape hatch. Don’t overuse it. React will **not** attempt to patch mismatched text content. +Isso funciona apenas em um nível de profundidade e destina-se a ser uma saída de emergência. Não o use em excesso. O React **não** tentará corrigir o conteúdo de texto incompatível. --- -### Handling different client and server content {/*handling-different-client-and-server-content*/} +### Lidando com conteúdo diferente no cliente e no servidor {/*handling-different-client-and-server-content*/} -If you intentionally need to render something different on the server and the client, you can do a two-pass rendering. Components that render something different on the client can read a [state variable](/reference/react/useState) like `isClient`, which you can set to `true` in an [Effect](/reference/react/useEffect): +Se você precisar intencionalmente renderizar algo diferente no servidor e no cliente, pode fazer uma renderização em duas passagens. Componentes que renderizam algo diferente no cliente podem ler uma [variável de estado](/reference/react/useState) como `isClient`, que você pode definir como `true` em um [Effect](/reference/react/useEffect): ```html public/index.html

Is Server

``` @@ -316,28 +315,28 @@ export default function App() {
-This way the initial render pass will render the same content as the server, avoiding mismatches, but an additional pass will happen synchronously right after hydration. +Dessa forma, a passagem de renderização inicial renderizará o mesmo conteúdo do servidor, evitando incompatibilidades, mas uma passagem adicional ocorrerá de forma síncrona logo após a hidratação. -This approach makes hydration slower because your components have to render twice. Be mindful of the user experience on slow connections. The JavaScript code may load significantly later than the initial HTML render, so rendering a different UI immediately after hydration may also feel jarring to the user. +Essa abordagem torna a hidratação mais lenta porque seus componentes precisam renderizar duas vezes. Tenha cuidado com a experiência do usuário em conexões lentas. O código JavaScript pode carregar significativamente depois da renderização HTML inicial, então renderizar uma interface diferente imediatamente após a hidratação também pode parecer chocante para o usuário. --- -### Updating a hydrated root component {/*updating-a-hydrated-root-component*/} +### Atualizando um componente raiz hidratado {/*updating-a-hydrated-root-component*/} -After the root has finished hydrating, you can call [`root.render`](#root-render) to update the root React component. **Unlike with [`createRoot`](/reference/react-dom/client/createRoot), you don't usually need to do this because the initial content was already rendered as HTML.** +Após a raiz terminar de hidratar, você pode chamar [`root.render`](#root-render) para atualizar o componente raiz React. **Ao contrário de [`createRoot`](/reference/react-dom/client/createRoot), você normalmente não precisa fazer isso porque o conteúdo inicial já foi renderizado como HTML.** -If you call `root.render` at some point after hydration, and the component tree structure matches up with what was previously rendered, React will [preserve the state.](/learn/preserving-and-resetting-state) Notice how you can type in the input, which means that the updates from repeated `render` calls every second in this example are not destructive: +Se você chamar `root.render` em algum momento após a hidratação, e a estrutura da árvore de componentes corresponder ao que foi renderizado anteriormente, o React [preservará o estado.](/learn/preserving-and-resetting-state) Observe como você pode digitar no input, o que significa que as atualizações das chamadas repetidas de `render` a cada segundo neste exemplo não são destrutivas: ```html public/index.html

Hello, world! 0

``` @@ -372,11 +371,11 @@ export default function App({counter}) {
-It is uncommon to call [`root.render`](#root-render) on a hydrated root. Usually, you'll [update state](/reference/react/useState) inside one of the components instead. +É incomum chamar [`root.render`](#root-render) em uma raiz hidratada. Geralmente, você [atualizará o estado](/reference/react/useState) dentro de um dos componentes em vez disso. -### Error logging in production {/*error-logging-in-production*/} +### Registro de erros em produção {/*error-logging-in-production*/} -By default, React will log all errors to the console. To implement your own error reporting, you can provide the optional error handler root options `onUncaughtError`, `onCaughtError` and `onRecoverableError`: +Por padrão, o React registrará todos os erros no console. Para implementar seu próprio relatório de erros, você pode fornecer as opções opcionais de raiz de manipulador de erros `onUncaughtError`, `onCaughtError` e `onRecoverableError`: ```js [[1, 7, "onCaughtError"], [2, 7, "error", 1], [3, 7, "errorInfo"], [4, 11, "componentStack", 15]] import { hydrateRoot } from "react-dom/client"; @@ -396,19 +395,19 @@ const root = hydrateRoot(container, , { }); ``` -The onCaughtError option is a function called with two arguments: +A opção onCaughtError é uma função chamada com dois argumentos: -1. The error that was thrown. -2. An errorInfo object that contains the componentStack of the error. +1. O erro que foi lançado. +2. Um objeto errorInfo que contém o componentStack do erro. -Together with `onUncaughtError` and `onRecoverableError`, you can implement your own error reporting system: +Junto com `onUncaughtError` e `onRecoverableError`, você pode implementar seu próprio sistema de relatório de erros: ```js src/reportError.js function reportError({ type, error, errorInfo }) { - // The specific implementation is up to you. - // `console.error()` is only used for demonstration purposes. + // A implementação específica depende de você. + // `console.error()` é usado apenas para fins de demonstração. console.error(type, error, "Component Stack: "); console.error("Component Stack: ", errorInfo.componentStack); } @@ -439,9 +438,9 @@ import { const container = document.getElementById("root"); hydrateRoot(container, , { - // Keep in mind to remove these options in development to leverage - // React's default handlers or implement your own overlay for development. - // The handlers are only specfied unconditionally here for demonstration purposes. + // Lembre-se de remover essas opções em desenvolvimento para aproveitar + // os manipuladores padrão do React ou implementar sua própria sobreposição para desenvolvimento. + // Os manipuladores são especificados incondicionalmente aqui apenas para fins de demonstração. onCaughtError: onCaughtErrorProd, onRecoverableError: onRecoverableErrorProd, onUncaughtError: onUncaughtErrorProd, @@ -501,7 +500,7 @@ export default function App() {
Server content before hydration.
@@ -509,12 +508,12 @@ export default function App() { ```
-## Troubleshooting {/*troubleshooting*/} +## Solução de problemas {/*troubleshooting*/} -### I'm getting an error: "You passed a second argument to root.render" {/*im-getting-an-error-you-passed-a-second-argument-to-root-render*/} +### Estou recebendo um erro: "You passed a second argument to root.render" {/*im-getting-an-error-you-passed-a-second-argument-to-root-render*/} -A common mistake is to pass the options for `hydrateRoot` to `root.render(...)`: +Um erro comum é passar as opções para `hydrateRoot` para `root.render(...)`: @@ -522,11 +521,11 @@ Warning: You passed a second argument to root.render(...) but it only accepts on -To fix, pass the root options to `hydrateRoot(...)`, not `root.render(...)`: +Para corrigir, passe as opções da raiz para `hydrateRoot(...)`, não para `root.render(...)`: ```js {2,5} -// 🚩 Wrong: root.render only takes one argument. +// 🚩 Errado: root.render aceita apenas um argumento. root.render(App, {onUncaughtError}); -// ✅ Correct: pass options to createRoot. +// ✅ Correto: passe as opções para createRoot. const root = hydrateRoot(container, , {onUncaughtError}); -``` +``` \ No newline at end of file