diff --git a/src/content/blog/2022/03/08/react-18-upgrade-guide.md b/src/content/blog/2022/03/08/react-18-upgrade-guide.md index 9d34dfaaa..b0b8b9443 100644 --- a/src/content/blog/2022/03/08/react-18-upgrade-guide.md +++ b/src/content/blog/2022/03/08/react-18-upgrade-guide.md @@ -1,92 +1,92 @@ --- -title: "How to Upgrade to React 18" +title: "Como Fazer Upgrade para o React 18" author: Rick Hanlon date: 2022/03/08 -description: As we shared in the release post, React 18 introduces features powered by our new concurrent renderer, with a gradual adoption strategy for existing applications. In this post, we will guide you through the steps for upgrading to React 18. +description: Como compartilhamos na postagem de lançamento, o React 18 introduz recursos alimentados pelo nosso novo renderizador concorrente, com uma estratégia de adoção gradual para aplicações existentes. Neste post, vamos orientá-lo pelas etapas para fazer upgrade para o React 18. --- -March 08, 2022 by [Rick Hanlon](https://twitter.com/rickhanlonii) +8 de março de 2022 por [Rick Hanlon](https://twitter.com/rickhanlonii) --- -As we shared in the [release post](/blog/2022/03/29/react-v18), React 18 introduces features powered by our new concurrent renderer, with a gradual adoption strategy for existing applications. In this post, we will guide you through the steps for upgrading to React 18. +Como compartilhamos na [postagem de lançamento](/blog/2022/03/29/react-v18), o React 18 introduz recursos alimentados pelo nosso novo renderizador concorrente, com uma estratégia de adoção gradual para aplicações existentes. Neste post, vamos orientá-lo pelas etapas para fazer upgrade para o React 18. -Please [report any issues](https://github.com/facebook/react/issues/new/choose) you encounter while upgrading to React 18. +Por favor, [relate quaisquer problemas](https://github.com/facebook/react/issues/new/choose) que encontrar ao fazer upgrade para o React 18. -For React Native users, React 18 will ship in a future version of React Native. This is because React 18 relies on the New React Native Architecture to benefit from the new capabilities presented in this blogpost. For more information, see the [React Conf keynote here](https://www.youtube.com/watch?v=FZ0cG47msEk&t=1530s). +Para usuários do React Native, o React 18 será incluído em uma versão futura do React Native. Isso ocorre porque o React 18 depende da Nova Arquitetura do React Native para beneficiar-se das novas capacidades apresentadas neste blogpost. Para mais informações, veja a [keynote do React Conf aqui](https://www.youtube.com/watch?v=FZ0cG47msEk&t=1530s). --- -## Installing {/*installing*/} +## Instalando {/*installing*/} -To install the latest version of React: +Para instalar a versão mais recente do React: ```bash npm install react react-dom ``` -Or if you’re using yarn: +Ou se você estiver usando yarn: ```bash yarn add react react-dom ``` -## Updates to Client Rendering APIs {/*updates-to-client-rendering-apis*/} +## Atualizações nas APIs de Renderização do Cliente {/*updates-to-client-rendering-apis*/} -When you first install React 18, you will see a warning in the console: +Quando você instalar o React 18 pela primeira vez, verá um aviso no console: -ReactDOM.render is no longer supported in React 18. Use createRoot instead. Until you switch to the new API, your app will behave as if it's running React 17. Learn more: https://reactjs.org/link/switch-to-createroot +ReactDOM.render não é mais suportado no React 18. Use createRoot em vez disso. Até você mudar para a nova API, seu aplicativo se comportará como se estivesse executando o React 17. Saiba mais: https://reactjs.org/link/switch-to-createroot -React 18 introduces a new root API which provides better ergonomics for managing roots. The new root API also enables the new concurrent renderer, which allows you to opt-into concurrent features. +O React 18 introduz uma nova API raiz que fornece melhor ergonomia para gerenciar raízes. A nova API raiz também permite o novo renderizador concorrente, que permite que você opte por recursos concorrentes. ```js -// Before +// Antes import { render } from 'react-dom'; const container = document.getElementById('app'); render(, container); -// After +// Depois import { createRoot } from 'react-dom/client'; const container = document.getElementById('app'); -const root = createRoot(container); // createRoot(container!) if you use TypeScript +const root = createRoot(container); // createRoot(container!) se você usar TypeScript root.render(); ``` -We’ve also changed `unmountComponentAtNode` to `root.unmount`: +Também mudamos `unmountComponentAtNode` para `root.unmount`: ```js -// Before +// Antes unmountComponentAtNode(container); -// After +// Depois root.unmount(); ``` -We've also removed the callback from render, since it usually does not have the expected result when using Suspense: +Também removemos o callback de renderização, uma vez que geralmente não tem o resultado esperado ao usar Suspense: ```js -// Before +// Antes const container = document.getElementById('app'); render(, container, () => { - console.log('rendered'); + console.log('renderizado'); }); -// After +// Depois function AppWithCallbackAfterRender() { useEffect(() => { - console.log('rendered'); + console.log('renderizado'); }); return @@ -99,59 +99,59 @@ root.render(); -There is no one-to-one replacement for the old render callback API — it depends on your use case. See the working group post for [Replacing render with createRoot](https://github.com/reactwg/react-18/discussions/5) for more information. +Não há um substituto exato para a antiga API de callback de renderização — depende do seu caso de uso. Veja a postagem do grupo de trabalho sobre [Substituindo render por createRoot](https://github.com/reactwg/react-18/discussions/5) para mais informações. -Finally, if your app uses server-side rendering with hydration, upgrade `hydrate` to `hydrateRoot`: +Finalmente, se seu aplicativo usar renderização do lado do servidor com hidratação, atualize `hydrate` para `hydrateRoot`: ```js -// Before +// Antes import { hydrate } from 'react-dom'; const container = document.getElementById('app'); hydrate(, container); -// After +// Depois import { hydrateRoot } from 'react-dom/client'; const container = document.getElementById('app'); const root = hydrateRoot(container, ); -// Unlike with createRoot, you don't need a separate root.render() call here. +// Ao contrário do createRoot, você não precisa de uma chamada separada root.render() aqui. ``` -For more information, see the [working group discussion here](https://github.com/reactwg/react-18/discussions/5). +Para mais informações, veja a [discussão do grupo de trabalho aqui](https://github.com/reactwg/react-18/discussions/5). -**If your app doesn't work after upgrading, check whether it's wrapped in ``.** [Strict Mode has gotten stricter in React 18](#updates-to-strict-mode), and not all your components may be resilient to the new checks it adds in development mode. If removing Strict Mode fixes your app, you can remove it during the upgrade, and then add it back (either at the top or for a part of the tree) after you fix the issues that it's pointing out. +**Se seu aplicativo não funcionar após o upgrade, verifique se está encapsulado em ``.** O [Modo Estrito ficou mais rigoroso no React 18](#updates-to-strict-mode), e nem todos os seus componentes podem ser resilientes às novas verificações que ele adiciona no modo de desenvolvimento. Se remover o Modo Estrito corrigir seu aplicativo, você pode removê-lo durante o upgrade e depois adicioná-lo novamente (seja no topo ou para uma parte da árvore) após corrigir os problemas que ele está apontando. -## Updates to Server Rendering APIs {/*updates-to-server-rendering-apis*/} +## Atualizações nas APIs de Renderização do Servidor {/*updates-to-server-rendering-apis*/} -In this release, we’re revamping our `react-dom/server` APIs to fully support Suspense on the server and Streaming SSR. As part of these changes, we're deprecating the old Node streaming API, which does not support incremental Suspense streaming on the server. +Nesta versão, estamos reformulando nossas APIs `react-dom/server` para suportar totalmente Suspense no servidor e Streaming SSR. Como parte dessas mudanças, estamos descontinuando a antiga API de streaming do Node, que não suporta streaming incremental de Suspense no servidor. -Using this API will now warn: +Usar esta API agora avisará: -* `renderToNodeStream`: **Deprecated ⛔️️** +* `renderToNodeStream`: **Descontinuado ⛔️️** -Instead, for streaming in Node environments, use: -* `renderToPipeableStream`: **New ✨** +Em vez disso, para streaming em ambientes Node, use: +* `renderToPipeableStream`: **Novo ✨** -We're also introducing a new API to support streaming SSR with Suspense for modern edge runtime environments, such as Deno and Cloudflare workers: -* `renderToReadableStream`: **New ✨** +Também estamos introduzindo uma nova API para suportar streaming SSR com Suspense em ambientes de execução moderna, como Deno e Cloudflare workers: +* `renderToReadableStream`: **Novo ✨** -The following APIs will continue working, but with limited support for Suspense: -* `renderToString`: **Limited** ⚠️ -* `renderToStaticMarkup`: **Limited** ⚠️ +As seguintes APIs continuarão funcionando, mas com suporte limitado para Suspense: +* `renderToString`: **Limitado** ⚠️ +* `renderToStaticMarkup`: **Limitado** ⚠️ -Finally, this API will continue to work for rendering e-mails: +Finalmente, esta API continuará a funcionar para renderização de e-mails: * `renderToStaticNodeStream` -For more information on the changes to server rendering APIs, see the working group post on [Upgrading to React 18 on the server](https://github.com/reactwg/react-18/discussions/22), a [deep dive on the new Suspense SSR Architecture](https://github.com/reactwg/react-18/discussions/37), and [Shaundai Person’s](https://twitter.com/shaundai) talk on [Streaming Server Rendering with Suspense](https://www.youtube.com/watch?v=pj5N-Khihgc) at React Conf 2021. +Para mais informações sobre as mudanças nas APIs de renderização do servidor, veja a postagem do grupo de trabalho sobre [Upgrade para o React 18 no servidor](https://github.com/reactwg/react-18/discussions/22), uma [análise profunda sobre a nova Arquitetura SSR do Suspense](https://github.com/reactwg/react-18/discussions/37), e a palestra de [Shaundai Person](https://twitter.com/shaundai) sobre [Streaming Server Rendering com Suspense](https://www.youtube.com/watch?v=pj5N-Khihgc) na React Conf 2021. -## Updates to TypeScript definitions {/*updates-to-typescript-definitions*/} +## Atualizações nas definições do TypeScript {/*updates-to-typescript-definitions*/} -If your project uses TypeScript, you will need to update your `@types/react` and `@types/react-dom` dependencies to the latest versions. The new types are safer and catch issues that used to be ignored by the type checker. The most notable change is that the `children` prop now needs to be listed explicitly when defining props, for example: +Se seu projeto usa TypeScript, você precisará atualizar suas dependências `@types/react` e `@types/react-dom` para as versões mais recentes. Os novos tipos são mais seguros e detectam problemas que costumavam ser ignorados pelo verificador de tipos. A mudança mais notável é que a prop `children` agora precisa ser listada explicitamente ao definir props, por exemplo: ```typescript{3} interface MyButtonProps { @@ -160,51 +160,50 @@ interface MyButtonProps { } ``` -See the [React 18 typings pull request](https://github.com/DefinitelyTyped/DefinitelyTyped/pull/56210) for a full list of type-only changes. It links to example fixes in library types so you can see how to adjust your code. You can use the [automated migration script](https://github.com/eps1lon/types-react-codemod) to help port your application code to the new and safer typings faster. +Veja a [pull request de tipagens do React 18](https://github.com/DefinitelyTyped/DefinitelyTyped/pull/56210) para uma lista completa das mudanças apenas nas tipagens. Ela liga a correções de exemplo nas tipagens de biblioteca para que você possa ver como ajustar seu código. Você pode usar o [script de migração automatizado](https://github.com/eps1lon/types-react-codemod) para ajudar a portar o código do seu aplicativo para as novas e mais seguras tipagens mais rapidamente. -If you find a bug in the typings, please [file an issue](https://github.com/DefinitelyTyped/DefinitelyTyped/discussions/new?category=issues-with-a-types-package) in the DefinitelyTyped repo. +Se você encontrar um bug nas tipagens, por favor, [registre um problema](https://github.com/DefinitelyTyped/DefinitelyTyped/discussions/new?category=issues-with-a-types-package) no repositório DefinitelyTyped. -## Automatic Batching {/*automatic-batching*/} +## Agrupamento Automático {/*automatic-batching*/} -React 18 adds out-of-the-box performance improvements by doing more batching by default. Batching is when React groups multiple state updates into a single re-render for better performance. Before React 18, we only batched updates inside React event handlers. Updates inside of promises, setTimeout, native event handlers, or any other event were not batched in React by default: +O React 18 adiciona melhorias de desempenho prontas para uso ao fazer mais agrupamento por padrão. Agrupamento é quando o React agrupa várias atualizações de estado em um único re-renderizador para melhor desempenho. Antes do React 18, agrupávamos apenas atualizações dentro dos manipuladores de eventos do React. Atualizações dentro de promessas, setTimeout, manipuladores de eventos nativos ou qualquer outro evento não eram agrupadas no React por padrão: ```js -// Before React 18 only React events were batched +// Antes do React 18, apenas eventos do React eram agrupados function handleClick() { setCount(c => c + 1); setFlag(f => !f); - // React will only re-render once at the end (that's batching!) + // O React re-renderizará apenas uma vez no final (isso é agrupamento!) } setTimeout(() => { setCount(c => c + 1); setFlag(f => !f); - // React will render twice, once for each state update (no batching) + // O React re-renderizará duas vezes, uma para cada atualização de estado (sem agrupamento) }, 1000); ``` - -Starting in React 18 with `createRoot`, all updates will be automatically batched, no matter where they originate from. This means that updates inside of timeouts, promises, native event handlers or any other event will batch the same way as updates inside of React events: +A partir do React 18 com `createRoot`, todas as atualizações serão agrupadas automaticamente, não importa de onde elas se originem. Isso significa que atualizações dentro de timeouts, promessas, manipuladores de eventos nativos ou qualquer outro evento serão agrupadas da mesma forma que atualizações dentro de eventos do React: ```js -// After React 18 updates inside of timeouts, promises, -// native event handlers or any other event are batched. +// Depois do React 18, atualizações dentro de timeouts, promessas, +// manipuladores de eventos nativos ou qualquer outro evento são agrupadas. function handleClick() { setCount(c => c + 1); setFlag(f => !f); - // React will only re-render once at the end (that's batching!) + // O React re-renderizará apenas uma vez no final (isso é agrupamento!) } setTimeout(() => { setCount(c => c + 1); setFlag(f => !f); - // React will only re-render once at the end (that's batching!) + // O React re-renderizará apenas uma vez no final (isso é agrupamento!) }, 1000); ``` -This is a breaking change, but we expect this to result in less work rendering, and therefore better performance in your applications. To opt-out of automatic batching, you can use `flushSync`: +Esta é uma mudança significativa, mas esperamos que isso resulte em menos trabalho de renderização e, portanto, melhor desempenho em suas aplicações. Para optar por não utilizar o agrupamento automático, você pode usar `flushSync`: ```js import { flushSync } from 'react-dom'; @@ -213,119 +212,119 @@ function handleClick() { flushSync(() => { setCounter(c => c + 1); }); - // React has updated the DOM by now + // O React já atualizou o DOM até agora flushSync(() => { setFlag(f => !f); }); - // React has updated the DOM by now + // O React já atualizou o DOM até agora } ``` -For more information, see the [Automatic batching deep dive](https://github.com/reactwg/react-18/discussions/21). +Para mais informações, veja a [análise profunda do agrupamento automático](https://github.com/reactwg/react-18/discussions/21). -## New APIs for Libraries {/*new-apis-for-libraries*/} +## Novas APIs para Bibliotecas {/*new-apis-for-libraries*/} -In the React 18 Working Group we worked with library maintainers to create new APIs needed to support concurrent rendering for use cases specific to their use case in areas like styles, and external stores. To support React 18, some libraries may need to switch to one of the following APIs: +No Grupo de Trabalho do React 18, trabalhamos com mantenedores de bibliotecas para criar novas APIs necessárias para suportar renderização concorrente para casos de uso específicos em áreas como estilos e armazenamentos externos. Para suportar o React 18, algumas bibliotecas podem precisar mudar para uma das seguintes APIs: -* `useSyncExternalStore` is a new Hook that allows external stores to support concurrent reads by forcing updates to the store to be synchronous. This new API is recommended for any library that integrates with state external to React. For more information, see the [useSyncExternalStore overview post](https://github.com/reactwg/react-18/discussions/70) and [useSyncExternalStore API details](https://github.com/reactwg/react-18/discussions/86). -* `useInsertionEffect` is a new Hook that allows CSS-in-JS libraries to address performance issues of injecting styles in render. Unless you've already built a CSS-in-JS library we don't expect you to ever use this. This Hook will run after the DOM is mutated, but before layout effects read the new layout. This solves an issue that already exists in React 17 and below, but is even more important in React 18 because React yields to the browser during concurrent rendering, giving it a chance to recalculate layout. For more information, see the [Library Upgrade Guide for `