diff --git a/src/content/blog/2024/04/25/react-19-upgrade-guide.md b/src/content/blog/2024/04/25/react-19-upgrade-guide.md index 4d4355a47..1a545a1a4 100644 --- a/src/content/blog/2024/04/25/react-19-upgrade-guide.md +++ b/src/content/blog/2024/04/25/react-19-upgrade-guide.md @@ -1,86 +1,86 @@ --- -title: "React 19 Beta Upgrade Guide" +title: "Guia de Atualização para o Beta do React 19" author: Ricky Hanlon date: 2024/04/25 -description: The improvements added to React 19 require some breaking changes, but we've worked to make the upgrade as smooth as possible and we don't expect the changes to impact most apps. In this post, we will guide you through the steps for upgrading libraries to React 19 beta. +description: As melhorias adicionadas ao React 19 requerem algumas mudanças que quebram a compatibilidade, mas trabalhamos para tornar a atualização o mais suave possível e não esperamos que as mudanças impactem a maioria dos aplicativos. Neste post, iremos orientá-lo pelos passos para atualizar as bibliotecas para o beta do React 19. --- -April 25, 2024 by [Ricky Hanlon](https://twitter.com/rickhanlonii) +25 de abril de 2024 por [Ricky Hanlon](https://twitter.com/rickhanlonii) --- -This beta release is for libraries to prepare for React 19. App developers should upgrade to 18.3.0 and wait for React 19 stable as we work with libraries and make changes based on feedback. +Esta versão beta é para bibliotecas se prepararem para o React 19. Desenvolvedores de aplicativos devem atualizar para 18.3.0 e aguardar o React 19 estável enquanto trabalhamos com as bibliotecas e fazemos alterações com base no feedback. -The improvements added to React 19 require some breaking changes, but we've worked to make the upgrade as smooth as possible and we don't expect the changes to impact most apps. +As melhorias adicionadas ao React 19 requerem algumas mudanças que quebram a compatibilidade, mas trabalhamos para tornar a atualização o mais suave possível e não esperamos que as mudanças impactem a maioria dos aplicativos. -To help make the upgrade easier, today we are also publishing React 18.3. +Para ajudar a tornar a atualização mais fácil, hoje também estamos publicando o React 18.3. -#### React 18.3 has also been published {/*react-18-3*/} +#### O React 18.3 também foi publicado {/*react-18-3*/} -To help make the upgrade to React 19 easier, we've published a `react@18.3` release that is identical to 18.2 but adds warnings for deprecated APIs and other changes that are needed for React 19. +Para ajudar a facilitar a atualização para o React 19, publicamos uma versão `react@18.3` que é idêntica à 18.2, mas adiciona avisos para APIs obsoletas e outras mudanças que são necessárias para o React 19. -We recommend upgrading to React 18.3 first to help identify any issues before upgrading to React 19. +Recomendamos atualizar para o React 18.3 primeiro para ajudar a identificar quaisquer problemas antes de atualizar para o React 19. -For a list of changes in 18.3 see the [Release Notes](https://github.com/facebook/react/blob/main/CHANGELOG.md). +Para uma lista de mudanças na 18.3, consulte as [Notas de Lançamento](https://github.com/facebook/react/blob/main/CHANGELOG.md). -In this post, we will guide you through the steps for upgrading libraries to React 19 beta: +Neste post, iremos orientá-lo pelos passos para atualizar as bibliotecas para o beta do React 19: -- [Installing](#installing) -- [Breaking changes](#breaking-changes) -- [New deprecations](#new-deprecations) -- [Notable changes](#notable-changes) -- [TypeScript changes](#typescript-changes) +- [Instalação](#installing) +- [Mudanças que quebram a compatibilidade](#breaking-changes) +- [Novas obsolências](#new-deprecations) +- [Mudanças notáveis](#notable-changes) +- [Mudanças no TypeScript](#typescript-changes) - [Changelog](#changelog) -If you'd like to help us test React 19, follow the steps in this upgrade guide and [report any issues](https://github.com/facebook/react/issues/new?assignees=&labels=React+19&projects=&template=19.md&title=%5BReact+19%5D) you encounter. For a list of new features added to React 19 beta, see the [React 19 release post](/blog/2024/04/25/react-19). +Se você gostaria de nos ajudar a testar o React 19, siga os passos neste guia de atualização e [relate quaisquer problemas](https://github.com/facebook/react/issues/new?assignees=&labels=React+19&projects=&template=19.md&title=%5BReact+19%5D) que você encontrar. Para uma lista de novos recursos adicionados ao beta do React 19, consulte o [post de lançamento do React 19](/blog/2024/04/25/react-19). --- -## Installing {/*installing*/} +## Instalação {/*installing*/} -#### New JSX Transform is now required {/*new-jsx-transform-is-now-required*/} +#### Novo JSX Transform agora é obrigatório {/*new-jsx-transform-is-now-required*/} -We introduced a [new JSX transform](https://legacy.reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html) in 2020 to improve bundle size and use JSX without importing React. In React 19, we're adding additional improvements like using ref as a prop and JSX speed improvements that require the new transform. +Introduzimos um [novo JSX transform](https://legacy.reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html) em 2020 para melhorar o tamanho do pacote e usar JSX sem importar o React. No React 19, estamos adicionando melhorias adicionais, como usar ref como uma prop e melhorias de velocidade no JSX que requerem o novo transform. -If the new transform is not enabled, you will see this warning: +Se o novo transform não estiver habilitado, você verá este aviso: -Your app (or one of its dependencies) is using an outdated JSX transform. Update to the modern JSX transform for faster performance: https://react.dev/link/new-jsx-transform +Seu aplicativo (ou uma de suas dependências) está usando um transform JSX obsoleto. Atualize para o transform JSX moderno para desempenho mais rápido: https://react.dev/link/new-jsx-transform -We expect most apps will not be affected since the transform is enabled in most environments already. For manual instructions on how to upgrade, please see the [announcement post](https://legacy.reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html). +Esperamos que a maioria dos aplicativos não seja afetada, já que o transform está habilitado em a maioria dos ambientes. Para instruções manuais sobre como atualizar, consulte o [post de anúncio](https://legacy.reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html). -To install the latest version of React and React DOM: +Para instalar a versão mais recente do React e do React DOM: ```bash npm install react@beta react-dom@beta ``` -If you're using TypeScript, you also need to update the types. Once React 19 is released as stable, you can install the types as usual from `@types/react` and `@types/react-dom`. During the beta period, the types are available in different packages which need to be enforced in your `package.json`: +Se você estiver usando TypeScript, também precisará atualizar os tipos. Assim que o React 19 for lançado como estável, você pode instalar os tipos normalmente a partir de `@types/react` e `@types/react-dom`. Durante o período beta, os tipos estão disponíveis em pacotes diferentes que precisam ser aplicados ao seu `package.json`: ```json { @@ -95,47 +95,47 @@ If you're using TypeScript, you also need to update the types. Once React 19 is } ``` -We're also including a codemod for the most common replacements. See [TypeScript changes](#typescript-changes) below. +Estamos também incluindo um codemod para as substituições mais comuns. Veja [Mudanças no TypeScript](#typescript-changes) abaixo. -## Breaking changes {/*breaking-changes*/} +## Mudanças que quebram a compatibilidade {/*breaking-changes*/} -### Errors in render are not re-thrown {/*errors-in-render-are-not-re-thrown*/} +### Erros na renderização não são relançados {/*errors-in-render-are-not-re-thrown*/} -In previous versions of React, errors thrown during render were caught and rethrown. In DEV, we would also log to `console.error`, resulting in duplicate error logs. +Em versões anteriores do React, erros lançados durante a renderização eram capturados e relançados. No modo DEV, também faríamos log em `console.error`, resultando em logs de erro duplicados. -In React 19, we've [improved how errors are handled](/blog/2024/04/25/react-19#error-handling) to reduce duplication by not re-throwing: +No React 19, [melhoramos como os erros são tratados](/blog/2024/04/25/react-19#error-handling) para reduzir duplicações, não relançando: -- **Uncaught Errors**: Errors that are not caught by an Error Boundary are reported to `window.reportError`. -- **Caught Errors**: Errors that are caught by an Error Boundary are reported to `console.error`. +- **Erros Não Capturados**: Erros que não são capturados por um Error Boundary são relatados para `window.reportError`. +- **Erros Capturados**: Erros que são capturados por um Error Boundary são relatados para `console.error`. -This change should not impact most apps, but if your production error reporting relies on errors being re-thrown, you may need to update your error handling. To support this, we've added new methods to `createRoot` and `hydrateRoot` for custom error handling: +Essa mudança não deve impactar a maioria dos aplicativos, mas se o seu relato de erros em produção depender do relançamento dos erros, você pode precisar atualizar seu manuseio de erros. Para suportar isso, adicionamos novos métodos a `createRoot` e `hydrateRoot` para manuseio personalizado de erros: ```js [[1, 2, "onUncaughtError"], [2, 5, "onCaughtError"]] const root = createRoot(container, { onUncaughtError: (error, errorInfo) => { - // ... log error report + // ... log de relato de erro }, onCaughtError: (error, errorInfo) => { - // ... log error report + // ... log de relato de erro } }); ``` -For more info, see the docs for [`createRoot`](https://react.dev/reference/react-dom/client/createRoot) and [`hydrateRoot`](https://react.dev/reference/react-dom/client/hydrateRoot). +Para mais informações, veja a documentação para [`createRoot`](https://react.dev/reference/react-dom/client/createRoot) e [`hydrateRoot`](https://react.dev/reference/react-dom/client/hydrateRoot). -### Removed deprecated React APIs {/*removed-deprecated-react-apis*/} +### APIs obsoletas do React removidas {/*removed-deprecated-react-apis*/} -#### Removed: `propTypes` and `defaultProps` for functions {/*removed-proptypes-and-defaultprops*/} -`PropTypes` were deprecated in [April 2017 (v15.5.0)](https://legacy.reactjs.org/blog/2017/04/07/react-v15.5.0.html#new-deprecation-warnings). +#### Removido: `propTypes` e `defaultProps` para funções {/*removed-proptypes-and-defaultprops*/} +`PropTypes` foram obsoletos em [abril de 2017 (v15.5.0)](https://legacy.reactjs.org/blog/2017/04/07/react-v15.5.0.html#new-deprecation-warnings). -In React 19, we're removing the `propType` checks from the React package, and using them will be silently ignored. If you're using `propTypes`, we recommend migrating to TypeScript or another type-checking solution. +No React 19, estamos removendo as verificações de `propType` do pacote React, e seu uso será silenciosamente ignorado. Se você estiver usando `propTypes`, recomendamos migrar para TypeScript ou outra solução de verificação de tipos. -We're also removing `defaultProps` from function components in place of ES6 default parameters. Class components will continue to support `defaultProps` since there is no ES6 alternative. +Também estamos removendo `defaultProps` de componentes de função em favor de parâmetros padrão do ES6. Componentes de classe continuarão a suportar `defaultProps`, já que não há alternativa no ES6. ```js -// Before +// Antes import PropTypes from 'prop-types'; function Heading({text}) { @@ -149,7 +149,7 @@ Heading.defaultProps = { }; ``` ```ts -// After +// Depois interface Props { text?: string; } @@ -158,16 +158,16 @@ function Heading({text = 'Hello, world!'}: Props) { } ``` -#### Removed: Legacy Context using `contextTypes` and `getChildContext` {/*removed-removing-legacy-context*/} +#### Removido: Contexto Legado usando `contextTypes` e `getChildContext` {/*removed-removing-legacy-context*/} -Legacy Context was deprecated in [October 2018 (v16.6.0)](https://legacy.reactjs.org/blog/2018/10/23/react-v-16-6.html). +O Contexto Legado foi obsoleto em [outubro de 2018 (v16.6.0)](https://legacy.reactjs.org/blog/2018/10/23/react-v-16-6.html). -Legacy Context was only available in class components using the APIs `contextTypes` and `getChildContext`, and was replaced with `contextType` due to subtle bugs that were easy to miss. In React 19, we're removing Legacy Context to make React slightly smaller and faster. +O Contexto Legado estava disponível apenas em componentes de classe usando as APIs `contextTypes` e `getChildContext`, e foi substituído por `contextType` devido a bugs sutis que eram fáceis de perder. No React 19, estamos removendo o Contexto Legado para tornar o React um pouco menor e mais rápido. -If you're still using Legacy Context in class components, you'll need to migrate to the new `contextType` API: +Se você ainda estiver usando o Contexto Legado em componentes de classe, precisará migrar para a nova API `contextType`: ```js {5-11,19-21} -// Before +// Antes import PropTypes from 'prop-types'; class Parent extends React.Component { @@ -196,7 +196,7 @@ class Child extends React.Component { ``` ```js {2,7,9,15} -// After +// Depois const FooContext = React.createContext(); class Parent extends React.Component { @@ -218,15 +218,15 @@ class Child extends React.Component { } ``` -#### Removed: string refs {/*removed-string-refs*/} -String refs were deprecated in [March, 2018 (v16.3.0)](https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html). +#### Removido: referências de string {/*removed-string-refs*/} +Referências de string foram obsoletas em [março de 2018 (v16.3.0)](https://legacy.reactjs.org/blog/2018/03/27/update-on-async-rendering.html). -Class components supported string refs before being replaced by ref callbacks due to [multiple downsides](https://github.com/facebook/react/issues/1373). In React 19, we're removing string refs to make React simpler and easier to understand. +Componentes de classe suportavam referências de string antes de serem substituídas por callbacks de ref devido a [vários pontos negativos](https://github.com/facebook/react/issues/1373). No React 19, estamos removendo referências de string para tornar o React mais simples e fácil de entender. -If you're still using string refs in class components, you'll need to migrate to ref callbacks: +Se você ainda estiver usando referências de string em componentes de classe, precisará migrar para callbacks de ref: ```js {4,8} -// Before +// Antes class MyComponent extends React.Component { componentDidMount() { this.refs.input.focus(); @@ -239,7 +239,7 @@ class MyComponent extends React.Component { ``` ```js {4,8} -// After +// Depois class MyComponent extends React.Component { componentDidMount() { this.input.focus(); @@ -253,49 +253,49 @@ class MyComponent extends React.Component { -To help with the migration, we will be publishing a [react-codemod](https://github.com/reactjs/react-codemod/#string-refs) to automatically replace string refs with `ref` callbacks. Follow [this PR](https://github.com/reactjs/react-codemod/pull/309) for updates and to try it out. +Para ajudar na migração, publicaremos um [react-codemod](https://github.com/reactjs/react-codemod/#string-refs) para substituir automaticamente referências de string por callbacks de ref. Siga [este PR](https://github.com/reactjs/react-codemod/pull/309) para atualizações e para experimentá-lo. -#### Removed: Module pattern factories {/*removed-module-pattern-factories*/} -Module pattern factories were deprecated in [August 2019 (v16.9.0)](https://legacy.reactjs.org/blog/2019/08/08/react-v16.9.0.html#deprecating-module-pattern-factories). +#### Removido: fábricas de padrão de módulo {/*removed-module-pattern-factories*/} +Fábricas de padrão de módulo foram obsoletas em [agosto de 2019 (v16.9.0)](https://legacy.reactjs.org/blog/2019/08/08/react-v16.9.0.html#deprecating-module-pattern-factories). -This pattern was rarely used and supporting it causes React to be slightly larger and slower than necessary. In React 19, we're removing support for module pattern factories, and you'll need to migrate to regular functions: +Esse padrão era raramente utilizado e seu suporte faz com que o React seja ligeiramente maior e mais lento do que o necessário. No React 19, estamos removendo o suporte para fábricas de padrão de módulo, e você precisará migrar para funções regulares: ```js -// Before +// Antes function FactoryComponent() { return { render() { return
; } } } ``` ```js -// After +// Depois function FactoryComponent() { return
; } ``` -#### Removed: `React.createFactory` {/*removed-createfactory*/} -`createFactory` was deprecated in [February 2020 (v16.13.0)](https://legacy.reactjs.org/blog/2020/02/26/react-v16.13.0.html#deprecating-createfactory). +#### Removido: `React.createFactory` {/*removed-createfactory*/} +`createFactory` foi obsoleto em [fevereiro de 2020 (v16.13.0)](https://legacy.reactjs.org/blog/2020/02/26/react-v16.13.0.html#deprecating-createfactory). -Using `createFactory` was common before broad support for JSX, but it's rarely used today and can be replaced with JSX. In React 19, we're removing `createFactory` and you'll need to migrate to JSX: +O uso de `createFactory` era comum antes do suporte amplo ao JSX, mas é raramente utilizado hoje e pode ser substituído por JSX. No React 19, estamos removendo `createFactory` e você precisará migrar para JSX: ```js -// Before +// Antes import { createFactory } from 'react'; const button = createFactory('button'); ``` ```js -// After +// Depois const button =