diff --git a/src/content/learn/build-a-react-app-from-scratch.md b/src/content/learn/build-a-react-app-from-scratch.md
index b5f29e9af..d4f4bff4f 100644
--- a/src/content/learn/build-a-react-app-from-scratch.md
+++ b/src/content/learn/build-a-react-app-from-scratch.md
@@ -1,143 +1,141 @@
---
-title: Build a React app from Scratch
+title: Construir uma Aplicação React do Zero
---
-If your app has constraints not well-served by existing frameworks, you prefer to build your own framework, or you just want to learn the basics of a React app, you can build a React app from scratch.
+Se sua aplicação tem restrições que não são bem atendidas pelos frameworks existentes, você prefere construir seu próprio framework, ou apenas quer aprender o básico de uma aplicação React, você pode construir uma aplicação React do zero.
-#### Consider using a framework {/*consider-using-a-framework*/}
+#### Considere usar um framework {/*consider-using-a-framework*/}
-Starting from scratch is an easy way to get started using React, but a major tradeoff to be aware of is that going this route is often the same as building your own adhoc framework. As your requirements evolve, you may need to solve more framework-like problems that our recommended frameworks already have well developed and supported solutions for.
+Começar do zero é uma maneira fácil de começar a usar React, mas um compromisso importante a ter em mente é que seguir este caminho é muitas vezes o mesmo que construir seu próprio framework ad hoc. À medida que seus requisitos evoluem, você pode precisar resolver mais problemas semelhantes a frameworks para os quais nossos frameworks recomendados já têm soluções bem desenvolvidas e suportadas.
-For example, if in the future your app needs support for server-side rendering (SSR), static site generation (SSG), and/or React Server Components (RSC), you will have to implement those on your own. Similarly, future React features that require integrating at the framework level will have to be implemented on your own if you want to use them.
+Por exemplo, se no futuro sua aplicação precisar de suporte para renderização do lado do servidor (SSR), geração de site estático (SSG), e/ou React Server Components (RSC), você terá que implementá-los por conta própria. Da mesma forma, futuras funcionalidades do React que requerem integração no nível do framework terão que ser implementadas por você se quiser usá-las.
-Our recommended frameworks also help you build better performing apps. For example, reducing or eliminating waterfalls from network requests makes for a better user experience. This might not be a high priority when you are building a toy project, but if your app gains users you may want to improve its performance.
+Nossos frameworks recomendados também ajudam você a construir aplicações com melhor performance. Por exemplo, reduzir ou eliminar cascatas de requisições de rede proporciona uma melhor experiência do usuário. Isso pode não ser uma alta prioridade quando você está construindo um projeto de teste, mas se sua aplicação ganhar usuários, você pode querer melhorar sua performance.
-Going this route also makes it more difficult to get support, since the way you develop routing, data-fetching, and other features will be unique to your situation. You should only choose this option if you are comfortable tackling these problems on your own, or if you’re confident that you will never need these features.
+Seguir este caminho também torna mais difícil obter suporte, já que a maneira como você desenvolve roteamento, busca de dados e outras funcionalidades será única para sua situação. Você deve escolher esta opção apenas se estiver confortável em lidar com esses problemas por conta própria, ou se estiver confiante de que nunca precisará dessas funcionalidades.
-For a list of recommended frameworks, check out [Creating a React App](/learn/creating-a-react-app).
+Para uma lista de frameworks recomendados, confira [Criando uma Aplicação React](/learn/creating-a-react-app).
+## Passo 1: Instalar uma ferramenta de build {/*step-1-install-a-build-tool*/}
-## Step 1: Install a build tool {/*step-1-install-a-build-tool*/}
-
-The first step is to install a build tool like `vite`, `parcel`, or `rsbuild`. These build tools provide features to package and run source code, provide a development server for local development and a build command to deploy your app to a production server.
+O primeiro passo é instalar uma ferramenta de build como `vite`, `parcel`, ou `rsbuild`. Essas ferramentas de build fornecem funcionalidades para empacotar e executar código fonte, fornecem um servidor de desenvolvimento para desenvolvimento local e um comando de build para fazer deploy da sua aplicação em um servidor de produção.
### Vite {/*vite*/}
-[Vite](https://vite.dev/) is a build tool that aims to provide a faster and leaner development experience for modern web projects.
+[Vite](https://vite.dev/) é uma ferramenta de build que visa fornecer uma experiência de desenvolvimento mais rápida e enxuta para projetos web modernos.
{`npm create vite@latest my-app -- --template react`}
-Vite is opinionated and comes with sensible defaults out of the box. Vite has a rich ecosystem of plugins to support fast refresh, JSX, Babel/SWC, and other common features. See Vite's [React plugin](https://vite.dev/plugins/#vitejs-plugin-react) or [React SWC plugin](https://vite.dev/plugins/#vitejs-plugin-react-swc) and [React SSR example project](https://vite.dev/guide/ssr.html#example-projects) to get started.
+Vite é opinativo e vem com padrões sensatos prontos para uso. Vite tem um rico ecossistema de plugins para suportar fast refresh, JSX, Babel/SWC, e outras funcionalidades comuns. Veja o [plugin React do Vite](https://vite.dev/plugins/#vitejs-plugin-react) ou [plugin React SWC](https://vite.dev/plugins/#vitejs-plugin-react-swc) e [projeto de exemplo React SSR](https://vite.dev/guide/ssr.html#example-projects) para começar.
-Vite is already being used as a build tool in one of our [recommended frameworks](/learn/creating-a-react-app): [React Router](https://reactrouter.com/start/framework/installation).
+Vite já está sendo usado como ferramenta de build em um dos nossos [frameworks recomendados](/learn/creating-a-react-app): [React Router](https://reactrouter.com/start/framework/installation).
### Parcel {/*parcel*/}
-[Parcel](https://parceljs.org/) combines a great out-of-the-box development experience with a scalable architecture that can take your project from just getting started to massive production applications.
+[Parcel](https://parceljs.org/) combina uma ótima experiência de desenvolvimento pronta para uso com uma arquitetura escalável que pode levar seu projeto desde o início até aplicações de produção massivas.
{`npm install --save-dev parcel`}
-Parcel supports fast refresh, JSX, TypeScript, Flow, and styling out of the box. See [Parcel's React recipe](https://parceljs.org/recipes/react/#getting-started) to get started.
+Parcel suporta fast refresh, JSX, TypeScript, Flow, e estilização prontos para uso. Veja a [receita React do Parcel](https://parceljs.org/recipes/react/#getting-started) para começar.
### Rsbuild {/*rsbuild*/}
-[Rsbuild](https://rsbuild.dev/) is an Rspack-powered build tool that provides a seamless development experience for React applications. It comes with carefully tuned defaults and performance optimizations ready to use.
+[Rsbuild](https://rsbuild.dev/) é uma ferramenta de build alimentada pelo Rspack que fornece uma experiência de desenvolvimento perfeita para aplicações React. Vem com padrões cuidadosamente ajustados e otimizações de performance prontas para uso.
{`npx create-rsbuild --template react`}
-Rsbuild includes built-in support for React features like fast refresh, JSX, TypeScript, and styling. See [Rsbuild's React guide](https://rsbuild.dev/guide/framework/react) to get started.
+Rsbuild inclui suporte integrado para funcionalidades React como fast refresh, JSX, TypeScript, e estilização. Veja o [guia React do Rsbuild](https://rsbuild.dev/guide/framework/react) para começar.
-#### Metro for React Native {/*react-native*/}
+#### Metro para React Native {/*react-native*/}
-If you're starting from scratch with React Native you'll need to use [Metro](https://metrobundler.dev/), the JavaScript bundler for React Native. Metro supports bundling for platforms like iOS and Android, but lacks many features when compared to the tools here. We recommend starting with Vite, Parcel, or Rsbuild unless your project requires React Native support.
+Se você está começando do zero com React Native, precisará usar o [Metro](https://metrobundler.dev/), o bundler JavaScript para React Native. Metro suporta bundling para plataformas como iOS e Android, mas carece de muitas funcionalidades quando comparado às ferramentas aqui. Recomendamos começar com Vite, Parcel, ou Rsbuild, a menos que seu projeto requeira suporte ao React Native.
-## Step 2: Build Common Application Patterns {/*step-2-build-common-application-patterns*/}
+## Passo 2: Construir Padrões Comuns de Aplicação {/*step-2-build-common-application-patterns*/}
-The build tools listed above start off with a client-only, single-page app (SPA), but don't include any further solutions for common functionality like routing, data fetching, or styling.
+As ferramentas de build listadas acima começam com uma aplicação de página única (SPA) apenas do lado do cliente, mas não incluem soluções adicionais para funcionalidades comuns como roteamento, busca de dados, ou estilização.
-The React ecosystem includes many tools for these problems. We've listed a few that are widely used as a starting point, but feel free to choose other tools if those work better for you.
+O ecossistema React inclui muitas ferramentas para esses problemas. Listamos algumas que são amplamente usadas como ponto de partida, mas sinta-se livre para escolher outras ferramentas se funcionarem melhor para você.
-### Routing {/*routing*/}
+### Roteamento {/*routing*/}
-Routing determines what content or pages to display when a user visits a particular URL. You need to set up a router to map URLs to different parts of your app. You'll also need to handle nested routes, route parameters, and query parameters. Routers can be configured within your code, or defined based on your component folder and file structures.
+Roteamento determina qual conteúdo ou páginas exibir quando um usuário visita uma URL específica. Você precisa configurar um roteador para mapear URLs para diferentes partes da sua aplicação. Você também precisará lidar com rotas aninhadas, parâmetros de rota e parâmetros de consulta. Os roteadores podem ser configurados dentro do seu código, ou definidos com base nas estruturas de pastas e arquivos dos seus componentes.
-Routers are a core part of modern applications, and are usually integrated with data fetching (including prefetching data for a whole page for faster loading), code splitting (to minimize client bundle sizes), and page rendering approaches (to decide how each page gets generated).
+Os roteadores são uma parte central das aplicações modernas, e geralmente são integrados com busca de dados (incluindo pré-busca de dados para uma página inteira para carregamento mais rápido), divisão de código (para minimizar tamanhos de bundle do cliente), e abordagens de renderização de página (para decidir como cada página é gerada).
-We suggest using:
+Sugerimos usar:
- [React Router](https://reactrouter.com/start/data/custom)
- [Tanstack Router](https://tanstack.com/router/latest)
+### Busca de Dados {/*data-fetching*/}
-### Data Fetching {/*data-fetching*/}
-
-Fetching data from a server or other data source is a key part of most applications. Doing this properly requires handling loading states, error states, and caching the fetched data, which can be complex.
+Buscar dados de um servidor ou outra fonte de dados é uma parte fundamental da maioria das aplicações. Fazer isso adequadamente requer lidar com estados de carregamento, estados de erro, e cache dos dados buscados, que pode ser complexo.
-Purpose-built data fetching libraries do the hard work of fetching and caching the data for you, letting you focus on what data your app needs and how to display it. These libraries are typically used directly in your components, but can also be integrated into routing loaders for faster pre-fetching and better performance, and in server rendering as well.
+Bibliotecas de busca de dados especializadas fazem o trabalho pesado de buscar e cachear os dados para você, permitindo que você se concentre em quais dados sua aplicação precisa e como exibi-los. Essas bibliotecas são tipicamente usadas diretamente nos seus componentes, mas também podem ser integradas em loaders de roteamento para pré-busca mais rápida e melhor performance, e também na renderização do servidor.
-Note that fetching data directly in components can lead to slower loading times due to network request waterfalls, so we recommend prefetching data in router loaders or on the server as much as possible! This allows a page's data to be fetched all at once as the page is being displayed.
+Note que buscar dados diretamente nos componentes pode levar a tempos de carregamento mais lentos devido a cascatas de requisições de rede, então recomendamos pré-buscar dados em loaders de roteador ou no servidor o máximo possível! Isso permite que os dados de uma página sejam buscados todos de uma vez conforme a página está sendo exibida.
-If you're fetching data from most backends or REST-style APIs, we suggest using:
+Se você está buscando dados da maioria dos backends ou APIs estilo REST, sugerimos usar:
- [React Query](https://react-query.tanstack.com/)
- [SWR](https://swr.vercel.app/)
- [RTK Query](https://redux-toolkit.js.org/rtk-query/overview)
-If you're fetching data from a GraphQL API, we suggest using:
+Se você está buscando dados de uma API GraphQL, sugerimos usar:
- [Apollo](https://www.apollographql.com/docs/react)
- [Relay](https://relay.dev/)
+### Divisão de Código {/*code-splitting*/}
-### Code-splitting {/*code-splitting*/}
+Divisão de código é o processo de quebrar sua aplicação em bundles menores que podem ser carregados sob demanda. O tamanho do código de uma aplicação aumenta com cada nova funcionalidade e dependência adicional. As aplicações podem se tornar lentas para carregar porque todo o código para a aplicação inteira precisa ser enviado antes que possa ser usado. Cache, redução de funcionalidades/dependências, e mover algum código para executar no servidor podem ajudar a mitigar o carregamento lento, mas são soluções incompletas que podem sacrificar funcionalidade se usadas em excesso.
-Code-splitting is the process of breaking your app into smaller bundles that can be loaded on demand. An app's code size increases with every new feature and additional dependency. Apps can become slow to load because all of the code for the entire app needs to be sent before it can be used. Caching, reducing features/dependencies, and moving some code to run on the server can help mitigate slow loading but are incomplete solutions that can sacrifice functionality if overused.
+Da mesma forma, se você depende das aplicações que usam seu framework para dividir o código, você pode encontrar situações onde o carregamento se torna mais lento do que se nenhuma divisão de código estivesse acontecendo. Por exemplo, [carregar preguiçosamente](/reference/react/lazy) um gráfico atrasa o envio do código necessário para renderizar o gráfico, dividindo o código do gráfico do resto da aplicação. [Parcel suporta divisão de código com React.lazy](https://parceljs.org/recipes/react/#code-splitting). No entanto, se o gráfico carrega seus dados *depois* que foi inicialmente renderizado, você agora está esperando duas vezes. Esta é uma cascata: ao invés de buscar os dados para o gráfico e enviar o código para renderizá-lo simultaneamente, você deve esperar cada passo completar um após o outro.
-Similarly, if you rely on the apps using your framework to split the code, you might encounter situations where loading becomes slower than if no code splitting were happening at all. For example, [lazily loading](/reference/react/lazy) a chart delays sending the code needed to render the chart, splitting the chart code from the rest of the app. [Parcel supports code splitting with React.lazy](https://parceljs.org/recipes/react/#code-splitting). However, if the chart loads its data *after* it has been initially rendered you are now waiting twice. This is a waterfall: rather than fetching the data for the chart and sending the code to render it simultaneously, you must wait for each step to complete one after the other.
+Dividir código por rota, quando integrado com bundling e busca de dados, pode reduzir o tempo de carregamento inicial da sua aplicação e o tempo que leva para o maior conteúdo visível da aplicação renderizar ([Largest Contentful Paint](https://web.dev/articles/lcp)).
-Splitting code by route, when integrated with bundling and data fetching, can reduce the initial load time of your app and the time it takes for the largest visible content of the app to render ([Largest Contentful Paint](https://web.dev/articles/lcp)).
+Para instruções de divisão de código, veja a documentação da sua ferramenta de build:
+- [Otimizações de build do Vite](https://v3.vitejs.dev/guide/features.html#build-optimizations)
+- [Divisão de código do Parcel](https://parceljs.org/features/code-splitting/)
+- [Divisão de código do Rsbuild](https://rsbuild.dev/guide/optimization/code-splitting)
-For code-splitting instructions, see your build tool docs:
-- [Vite build optimizations](https://vite.dev/guide/features.html#build-optimizations)
-- [Parcel code splitting](https://parceljs.org/features/code-splitting/)
-- [Rsbuild code splitting](https://rsbuild.dev/guide/optimization/code-splitting)
-### Improving Application Performance {/*improving-application-performance*/}
+### Melhorando a Performance da Aplicação {/*improving-application-performance*/}
-Since the build tool you select only support single page apps (SPAs) you'll need to implement other [rendering patterns](https://www.patterns.dev/vanilla/rendering-patterns) like server-side rendering (SSR), static site generation (SSG), and/or React Server Components (RSC). Even if you don't need these features at first, in the future there may be some routes that would benefit SSR, SSG or RSC.
+Como a ferramenta de build que você seleciona só suporta aplicações de página única (SPAs), você precisará implementar outros [padrões de renderização](https://www.patterns.dev/vanilla/rendering-patterns) como renderização do lado do servidor (SSR), geração de site estático (SSG), e/ou React Server Components (RSC). Mesmo se você não precisar dessas funcionalidades no início, no futuro pode haver algumas rotas que se beneficiariam de SSR, SSG ou RSC.
-* **Single-page apps (SPA)** load a single HTML page and dynamically updates the page as the user interacts with the app. SPAs are easier to get started with, but they can have slower initial load times. SPAs are the default architecture for most build tools.
+* **Aplicações de página única (SPA)** carregam uma única página HTML e atualizam dinamicamente a página conforme o usuário interage com a aplicação. SPAs são mais fáceis de começar, mas podem ter tempos de carregamento inicial mais lentos. SPAs são a arquitetura padrão para a maioria das ferramentas de build.
-* **Streaming Server-side rendering (SSR)** renders a page on the server and sends the fully rendered page to the client. SSR can improve performance, but it can be more complex to set up and maintain than a single-page app. With the addition of streaming, SSR can be very complex to set up and maintain. See [Vite's SSR guide]( https://vite.dev/guide/ssr).
+* **Renderização do lado do servidor com streaming (SSR)** renderiza uma página no servidor e envia a página totalmente renderizada para o cliente. SSR pode melhorar a performance, mas pode ser mais complexo de configurar e manter do que uma aplicação de página única. Com a adição de streaming, SSR pode ser muito complexo de configurar e manter. Veja o [guia SSR do Vite](https://vite.dev/guide/ssr).
-* **Static site generation (SSG)** generates static HTML files for your app at build time. SSG can improve performance, but it can be more complex to set up and maintain than server-side rendering. See [Vite's SSG guide](https://vite.dev/guide/ssr.html#pre-rendering-ssg).
+* **Geração de site estático (SSG)** gera arquivos HTML estáticos para sua aplicação no momento do build. SSG pode melhorar a performance, mas pode ser mais complexo de configurar e manter do que renderização do lado do servidor. Veja o [guia SSG do Vite](https://vite.dev/guide/ssr.html#pre-rendering-ssg).
-* **React Server Components (RSC)** lets you mix build-time, server-only, and interactive components in a single React tree. RSC can improve performance, but it currently requires deep expertise to set up and maintain. See [Parcel's RSC examples](https://github.com/parcel-bundler/rsc-examples).
+* **React Server Components (RSC)** permite misturar componentes de build-time, apenas do servidor, e interativos em uma única árvore React. RSC pode melhorar a performance, mas atualmente requer expertise profunda para configurar e manter. Veja os [exemplos RSC do Parcel](https://github.com/parcel-bundler/rsc-examples).
-Your rendering strategies need to integrate with your router so apps built with your framework can choose the rendering strategy on a per-route level. This will enable different rendering strategies without having to rewrite your whole app. For example, the landing page for your app might benefit from being statically generated (SSG), while a page with a content feed might perform best with server-side rendering.
+Suas estratégias de renderização precisam se integrar com seu roteador para que aplicações construídas com seu framework possam escolher a estratégia de renderização no nível de rota. Isso permitirá diferentes estratégias de renderização sem ter que reescrever toda a sua aplicação. Por exemplo, a página de destino da sua aplicação pode se beneficiar de ser gerada estaticamente (SSG), enquanto uma página com um feed de conteúdo pode ter melhor performance com renderização do lado do servidor.
-Using the right rendering strategy for the right routes can decrease the time it takes for the first byte of content to be loaded ([Time to First Byte](https://web.dev/articles/ttfb)), the first piece of content to render ([First Contentful Paint](https://web.dev/articles/fcp)), and the largest visible content of the app to render ([Largest Contentful Paint](https://web.dev/articles/lcp)).
+Usar a estratégia de renderização certa para as rotas certas pode diminuir o tempo que leva para o primeiro byte de conteúdo ser carregado ([Time to First Byte](https://web.dev/articles/ttfb)), o primeiro pedaço de conteúdo renderizar ([First Contentful Paint](https://web.dev/articles/fcp)), e o maior conteúdo visível da aplicação renderizar ([Largest Contentful Paint](https://web.dev/articles/lcp)).
-### And more... {/*and-more*/}
+### E mais... {/*and-more*/}
-These are just a few examples of the features a new app will need to consider when building from scratch. Many limitations you'll hit can be difficult to solve as each problem is interconnected with the others and can require deep expertise in problem areas you may not be familiar with.
+Estes são apenas alguns exemplos das funcionalidades que uma nova aplicação precisará considerar ao construir do zero. Muitas limitações que você encontrará podem ser difíceis de resolver, já que cada problema está interconectado com os outros e pode requerer expertise profunda em áreas problemáticas com as quais você pode não estar familiarizado.
-If you don't want to solve these problems on your own, you can [get started with a framework](/learn/creating-a-react-app) that provides these features out of the box.
+Se você não quer resolver esses problemas por conta própria, pode [começar com um framework](/learn/creating-a-react-app) que fornece essas funcionalidades prontas para uso.
\ No newline at end of file
diff --git a/src/content/learn/creating-a-react-app.md b/src/content/learn/creating-a-react-app.md
index df512cca8..d7480ae32 100644
--- a/src/content/learn/creating-a-react-app.md
+++ b/src/content/learn/creating-a-react-app.md
@@ -1,94 +1,94 @@
---
-title: Creating a React App
+title: Criando uma Aplicação React
---
-If you want to build a new app or website with React, we recommend starting with a framework.
+Se você quer construir uma nova aplicação ou website com React, recomendamos começar com um framework.
-If your app has constraints not well-served by existing frameworks, you prefer to build your own framework, or you just want to learn the basics of a React app, you can [build a React app from scratch](/learn/build-a-react-app-from-scratch).
+Se sua aplicação tem restrições que não são bem atendidas pelos frameworks existentes, você prefere construir seu próprio framework, ou apenas quer aprender o básico de uma aplicação React, você pode [construir uma aplicação React do zero](/learn/build-a-react-app-from-scratch).
-## Full-stack frameworks {/*full-stack-frameworks*/}
+## Frameworks full-stack {/*full-stack-frameworks*/}
-These recommended frameworks support all the features you need to deploy and scale your app in production. They have integrated the latest React features and take advantage of React’s architecture.
+Estes frameworks recomendados suportam todas as funcionalidades que você precisa para fazer deploy e escalar sua aplicação em produção. Eles integraram as funcionalidades mais recentes do React e aproveitam a arquitetura do React.
-#### Full-stack frameworks do not require a server. {/*react-frameworks-do-not-require-a-server*/}
+#### Frameworks full-stack não requerem um servidor. {/*react-frameworks-do-not-require-a-server*/}
-All the frameworks on this page support client-side rendering ([CSR](https://developer.mozilla.org/en-US/docs/Glossary/CSR)), single-page apps ([SPA](https://developer.mozilla.org/en-US/docs/Glossary/SPA)), and static-site generation ([SSG](https://developer.mozilla.org/en-US/docs/Glossary/SSG)). These apps can be deployed to a [CDN](https://developer.mozilla.org/en-US/docs/Glossary/CDN) or static hosting service without a server. Additionally, these frameworks allow you to add server-side rendering on a per-route basis, when it makes sense for your use case.
+Todos os frameworks nesta página suportam renderização do lado do cliente ([CSR](https://developer.mozilla.org/en-US/docs/Glossary/CSR)), aplicações de página única ([SPA](https://developer.mozilla.org/en-US/docs/Glossary/SPA)), e geração de site estático ([SSG](https://developer.mozilla.org/en-US/docs/Glossary/SSG)). Essas aplicações podem ser deployadas em uma [CDN](https://developer.mozilla.org/en-US/docs/Glossary/CDN) ou serviço de hospedagem estática sem um servidor. Além disso, esses frameworks permitem que você adicione renderização do lado do servidor rota por rota, quando faz sentido para seu caso de uso.
-This allows you to start with a client-only app, and if your needs change later, you can opt-in to using server features on individual routes without rewriting your app. See your framework's documentation for configuring the rendering strategy.
+Isso permite que você comece com uma aplicação apenas do lado do cliente, e se suas necessidades mudarem depois, você pode optar por usar funcionalidades de servidor em rotas individuais sem reescrever sua aplicação. Veja a documentação do seu framework para configurar a estratégia de renderização.
### Next.js (App Router) {/*nextjs-app-router*/}
-**[Next.js's App Router](https://nextjs.org/docs) is a React framework that takes full advantage of React's architecture to enable full-stack React apps.**
+**[O App Router do Next.js](https://nextjs.org/docs) é um framework React que aproveita completamente a arquitetura do React para permitir aplicações React full-stack.**
npx create-next-app@latest
-Next.js is maintained by [Vercel](https://vercel.com/). You can [deploy a Next.js app](https://nextjs.org/docs/app/building-your-application/deploying) to any hosting provider that supports Node.js or Docker containers, or to your own server. Next.js also supports [static export](https://nextjs.org/docs/app/building-your-application/deploying/static-exports) which doesn't require a server.
+Next.js é mantido pela [Vercel](https://vercel.com/). Você pode [fazer deploy de uma aplicação Next.js](https://nextjs.org/docs/app/building-your-application/deploying) para qualquer hospedagem Node.js ou serverless, ou para seu próprio servidor. Next.js também suporta [exportação estática](https://nextjs.org/docs/app/building-your-application/deploying/static-exports) que não requer um servidor. A Vercel também fornece serviços em nuvem pagos opcionais.
+
### React Router (v7) {/*react-router-v7*/}
-**[React Router](https://reactrouter.com/start/framework/installation) is the most popular routing library for React and can be paired with Vite to create a full-stack React framework**. It emphasizes standard Web APIs and has several [ready to deploy templates](https://github.com/remix-run/react-router-templates) for various JavaScript runtimes and platforms.
+**[React Router](https://reactrouter.com/start/framework/installation) é a biblioteca de roteamento mais popular para React e pode ser pareada com Vite para criar um framework React full-stack**. Ele enfatiza APIs Web padrão e tem vários [templates prontos para deploy](https://github.com/remix-run/react-router-templates) para vários runtimes JavaScript e plataformas.
-To create a new React Router framework project, run:
+Para criar um novo projeto de framework React Router, execute:
npx create-react-router@latest
-React Router is maintained by [Shopify](https://www.shopify.com).
+React Router é mantido pela [Shopify](https://www.shopify.com).
-### Expo (for native apps) {/*expo*/}
+### Expo (para aplicações nativas) {/*expo*/}
-**[Expo](https://expo.dev/) is a React framework that lets you create universal Android, iOS, and web apps with truly native UIs.** It provides an SDK for [React Native](https://reactnative.dev/) that makes the native parts easier to use. To create a new Expo project, run:
+**[Expo](https://expo.dev/) é um framework React que permite criar aplicações universais para Android, iOS, e web com interfaces verdadeiramente nativas.** Ele fornece um SDK para [React Native](https://reactnative.dev/) que torna as partes nativas mais fáceis de usar. Para criar um novo projeto Expo, execute:
npx create-expo-app@latest
-If you're new to Expo, check out the [Expo tutorial](https://docs.expo.dev/tutorial/introduction/).
-
-Expo is maintained by [Expo (the company)](https://expo.dev/about). Building apps with Expo is free, and you can submit them to the Google and Apple app stores without restrictions. Expo additionally provides opt-in paid cloud services.
+Se você é novo no Expo, confira o [tutorial do Expo](https://docs.expo.dev/tutorial/introduction/).
+Expo é mantido pela [Expo (a empresa)](https://expo.dev/about). Construir aplicações com Expo é gratuito, e você pode enviá-las para as app stores do Google e Apple sem restrições. Expo também fornece serviços em nuvem pagos opcionais.
-## Other frameworks {/*other-frameworks*/}
+## Outros frameworks {/*other-frameworks*/}
-There are other up-and-coming frameworks that are working towards our full stack React vision:
+Existem outros frameworks emergentes que estão trabalhando em direção à nossa visão de React full-stack:
-- [TanStack Start (Beta)](https://tanstack.com/): TanStack Start is a full-stack React framework powered by TanStack Router. It provides a full-document SSR, streaming, server functions, bundling, and more using tools like Nitro and Vite.
-- [RedwoodJS](https://redwoodjs.com/): Redwood is a full stack React framework with lots of pre-installed packages and configuration that makes it easy to build full-stack web applications.
+- [TanStack Start (Beta)](https://tanstack.com/): TanStack Start é um framework React full-stack alimentado pelo TanStack Router. Ele fornece SSR de documento completo, streaming, funções de servidor, bundling, e mais usando ferramentas como Nitro e Vite.
+- [RedwoodJS](https://redwoodjs.com/): Redwood é um framework React full-stack com muitos pacotes pré-instalados e configuração que torna fácil construir aplicações web full-stack.
-#### Which features make up the React team’s full-stack architecture vision? {/*which-features-make-up-the-react-teams-full-stack-architecture-vision*/}
+#### Quais funcionalidades compõem a visão de arquitetura full-stack da equipe React? {/*which-features-make-up-the-react-teams-full-stack-architecture-vision*/}
-Next.js's App Router bundler fully implements the official [React Server Components specification](https://github.com/reactjs/rfcs/blob/main/text/0188-server-components.md). This lets you mix build-time, server-only, and interactive components in a single React tree.
+O bundler App Router do Next.js implementa completamente a [especificação oficial dos React Server Components](https://github.com/reactjs/rfcs/blob/main/text/0188-server-components.md). Isso permite misturar componentes de build-time, apenas do servidor, e interativos em uma única árvore React.
-For example, you can write a server-only React component as an `async` function that reads from a database or from a file. Then you can pass data down from it to your interactive components:
+Por exemplo, você pode escrever um componente React apenas do servidor como uma função `async` que lê de um banco de dados ou de um arquivo. Então você pode passar dados para baixo para seus componentes interativos:
```js
-// This component runs *only* on the server (or during the build).
+// Este componente executa *apenas* no servidor (ou durante o build).
async function Talks({ confId }) {
- // 1. You're on the server, so you can talk to your data layer. API endpoint not required.
+ // 1. Você está no servidor, então pode conversar com sua camada de dados. Endpoint de API não é necessário.
const talks = await db.Talks.findAll({ confId });
- // 2. Add any amount of rendering logic. It won't make your JavaScript bundle larger.
+ // 2. Adicione qualquer quantidade de lógica de renderização. Isso não tornará seu bundle JavaScript maior.
const videos = talks.map(talk => talk.video);
- // 3. Pass the data down to the components that will run in the browser.
+ // 3. Passe os dados para baixo para os componentes que executarão no navegador.
return ;
}
```
-Next.js's App Router also integrates [data fetching with Suspense](/blog/2022/03/29/react-v18#suspense-in-data-frameworks). This lets you specify a loading state (like a skeleton placeholder) for different parts of your user interface directly in your React tree:
+O App Router do Next.js também integra [busca de dados com Suspense](/blog/2022/03/29/react-v18#suspense-in-data-frameworks). Isso permite especificar um estado de carregamento (como um placeholder skeleton) para diferentes partes da sua interface de usuário diretamente na sua árvore React:
```js
}>
@@ -96,18 +96,16 @@ Next.js's App Router also integrates [data fetching with Suspense](/blog/2022/03
```
-Server Components and Suspense are React features rather than Next.js features. However, adopting them at the framework level requires buy-in and non-trivial implementation work. At the moment, the Next.js App Router is the most complete implementation. The React team is working with bundler developers to make these features easier to implement in the next generation of frameworks.
+Server Components e Suspense são funcionalidades do React ao invés de funcionalidades do Next.js. No entanto, adotá-las no nível do framework requer buy-in e trabalho de implementação não trivial. No momento, o App Router do Next.js é a implementação mais completa. A equipe React está trabalhando com desenvolvedores de bundlers para tornar essas funcionalidades mais fáceis de implementar na próxima geração de frameworks.
-## Start From Scratch {/*start-from-scratch*/}
-
-If your app has constraints not well-served by existing frameworks, you prefer to build your own framework, or you just want to learn the basics of a React app, there are other options available for starting a React project from scratch.
+## Começar do Zero {/*start-from-scratch*/}
-Starting from scratch gives you more flexibility, but does require that you make choices on which tools to use for routing, data fetching, and other common usage patterns. It's a lot like building your own framework, instead of using a framework that already exists. The [frameworks we recommend](#full-stack-frameworks) have built-in solutions for these problems.
+Se sua aplicação tem restrições que não são bem atendidas pelos frameworks existentes, você prefere construir seu próprio framework, ou apenas quer aprender o básico de uma aplicação React, existem outras opções disponíveis para começar um projeto React do zero.
-If you want to build your own solutions, see our guide to [build a React app from Scratch](/learn/build-a-react-app-from-scratch) for instructions on how to set up a new React project starting with a build tool like [Vite](https://vite.dev/), [Parcel](https://parceljs.org/), or [RSbuild](https://rsbuild.dev/).
+Começar do zero te dá mais flexibilidade, mas requer que você faça escolhas sobre quais ferramentas usar para roteamento, busca de dados, e outros padrões de uso comuns. É muito parecido com construir seu próprio framework, ao invés de usar um framework que já existe. Os [frameworks que recomendamos](#full-stack-frameworks) têm soluções integradas para esses problemas.
------
+Se você quer construir suas próprias soluções, veja nosso guia para [construir uma aplicação React do Zero](/learn/build-a-react-app-from-scratch) para instruções sobre como configurar um novo projeto React começando com uma ferramenta de build como [Vite](https://vite.dev/), [Parcel](https://parceljs.org/), ou [RSbuild](https://rsbuild.dev/).
-_If you’re a framework author interested in being included on this page, [please let us know](https://github.com/reactjs/react.dev/issues/new?assignees=&labels=type%3A+framework&projects=&template=3-framework.yml&title=%5BFramework%5D%3A+)._
+_Se você é um autor de framework interessado em ser incluído nesta página, [por favor nos informe](https://github.com/reactjs/react.dev/issues/new?assignees=&labels=type%3A+framework&projects=&template=3-framework.yml&title=%5BFramework%5D%3A+)._
\ No newline at end of file
diff --git a/src/content/learn/react-compiler.md b/src/content/learn/react-compiler.md
index 9d4e19d21..1acd3a84a 100644
--- a/src/content/learn/react-compiler.md
+++ b/src/content/learn/react-compiler.md
@@ -3,66 +3,71 @@ title: React Compiler
---
-This page will give you an introduction to React Compiler and how to try it out successfully.
+Esta página dará uma introdução ao React Compiler e como experimentá-lo com sucesso.
+
+Esta documentação ainda está em desenvolvimento. Mais documentação está disponível no [repositório do React Compiler Working Group](https://github.com/reactwg/react-compiler/discussions), e será integrada nesta documentação quando estiver mais estável.
+
+
-* Getting started with the compiler
-* Installing the compiler and ESLint plugin
-* Troubleshooting
+* Primeiros passos com o compilador
+* Instalação do compilador e plugin ESLint
+* Resolução de problemas
-React Compiler is a new compiler currently in RC, that we've open sourced to get feedback from the community. We now recommend everyone to try the compiler and provide feedback.
+O React Compiler é um novo compilador atualmente em Beta, que disponibilizámos como código aberto para obter feedback inicial da comunidade. Embora tenha sido usado em produção em empresas como a Meta, implementar o compilador em produção para a sua aplicação dependerá da saúde da sua base de código e de quão bem seguiu as [Regras do React](/reference/rules).
-The latest RC release can be found with the `@rc` tag, and daily experimental releases with `@experimental`.
+A versão Beta mais recente pode ser encontrada com a tag `@beta`, e versões experimentais diárias com `@experimental`.
-React Compiler is a new compiler that we've open sourced to get feedback from the community. It is a build-time only tool that automatically optimizes your React app. It works with plain JavaScript, and understands the [Rules of React](/reference/rules), so you don't need to rewrite any code to use it.
+O React Compiler é um novo compilador que disponibilizámos como código aberto para obter feedback inicial da comunidade. É uma ferramenta apenas de tempo de compilação que otimiza automaticamente a sua aplicação React. Funciona com JavaScript simples, e compreende as [Regras do React](/reference/rules), pelo que não precisa de reescrever nenhum código para o usar.
+
+O compilador também inclui um [plugin ESLint](#installing-eslint-plugin-react-compiler) que exibe a análise do compilador diretamente no seu editor. **Recomendamos vivamente que todos usem o linter hoje.** O linter não requer que tenha o compilador instalado, pelo que pode usá-lo mesmo que não esteja pronto para experimentar o compilador.
-eslint-plugin-react-hooks also includes an [ESLint rule](#installing-eslint-plugin-react-compiler) that surfaces the analysis from the compiler right in your editor. **We strongly recommend everyone use the linter today.** The linter does not require that you have the compiler installed, so you can use it even if you are not ready to try out the compiler.
+O compilador está atualmente lançado como `beta`, e está disponível para experimentar em aplicações e bibliotecas React 17+. Para instalar a Beta:
-The compiler is currently released as `rc`, and is available to try out on React 17+ apps and libraries. To install the RC:
{`npm install -D babel-plugin-react-compiler@rc eslint-plugin-react-hooks@^6.0.0-rc.1`}
-Or, if you're using Yarn:
+Ou, se estiver a usar Yarn:
{`yarn add -D babel-plugin-react-compiler@rc eslint-plugin-react-hooks@^6.0.0-rc.1`}
-If you are not using React 19 yet, please see [the section below](#using-react-compiler-with-react-17-or-18) for further instructions.
+Se ainda não estiver a usar React 19, por favor consulte [a secção abaixo](#using-react-compiler-with-react-17-or-18) para mais instruções.
-### What does the compiler do? {/*what-does-the-compiler-do*/}
+### O que faz o compilador? {/*what-does-the-compiler-do*/}
-In order to optimize applications, React Compiler automatically memoizes your code. You may be familiar today with memoization through APIs such as `useMemo`, `useCallback`, and `React.memo`. With these APIs you can tell React that certain parts of your application don't need to recompute if their inputs haven't changed, reducing work on updates. While powerful, it's easy to forget to apply memoization or apply them incorrectly. This can lead to inefficient updates as React has to check parts of your UI that don't have any _meaningful_ changes.
+Para otimizar aplicações, o React Compiler memoriza automaticamente o seu código. Pode estar familiarizado hoje com memorização através de APIs como `useMemo`, `useCallback`, e `React.memo`. Com estas APIs pode dizer ao React que certas partes da sua aplicação não precisam de ser recalculadas se as suas entradas não mudaram, reduzindo o trabalho nas atualizações. Embora poderosas, é fácil esquecer-se de aplicar memorização ou aplicá-las incorretamente. Isto pode levar a atualizações ineficientes, já que o React tem de verificar partes da sua UI que não têm mudanças _significativas_.
-The compiler uses its knowledge of JavaScript and React's rules to automatically memoize values or groups of values within your components and hooks. If it detects breakages of the rules, it will automatically skip over just those components or hooks, and continue safely compiling other code.
+O compilador usa o seu conhecimento de JavaScript e das regras do React para memorizar automaticamente valores ou grupos de valores dentro dos seus componentes e hooks. Se detetar quebras das regras, saltará automaticamente apenas esses componentes ou hooks, e continuará a compilar com segurança outro código.
-React Compiler can statically detect when Rules of React are broken, and safely opt-out of optimizing just the affected components or hooks. It is not necessary for the compiler to optimize 100% of your codebase.
+O React Compiler pode detetar estaticamente quando as Regras do React são quebradas, e optar com segurança por não otimizar apenas os componentes ou hooks afetados. Não é necessário que o compilador otimize 100% da sua base de código.
-If your codebase is already very well-memoized, you might not expect to see major performance improvements with the compiler. However, in practice memoizing the correct dependencies that cause performance issues is tricky to get right by hand.
+Se a sua base de código já está muito bem memorizada, pode não esperar ver grandes melhorias de desempenho com o compilador. No entanto, na prática, memorizar as dependências corretas que causam problemas de desempenho é complicado de acertar manualmente.
-#### What kind of memoization does React Compiler add? {/*what-kind-of-memoization-does-react-compiler-add*/}
+#### Que tipo de memorização adiciona o React Compiler? {/*what-kind-of-memoization-does-react-compiler-add*/}
-The initial release of React Compiler is primarily focused on **improving update performance** (re-rendering existing components), so it focuses on these two use cases:
+O lançamento inicial do React Compiler está principalmente focado em **melhorar o desempenho de atualizações** (re-renderizar componentes existentes), pelo que se foca nestes dois casos de uso:
-1. **Skipping cascading re-rendering of components**
- * Re-rendering `` causes many components in its component tree to re-render, even though only `` has changed
-1. **Skipping expensive calculations from outside of React**
- * For example, calling `expensivelyProcessAReallyLargeArrayOfObjects()` inside of your component or hook that needs that data
+1. **Saltar re-renderização em cascata de componentes**
+ * Re-renderizar `` faz com que muitos componentes na sua árvore de componentes se re-renderizem, mesmo que apenas `` tenha mudado
+1. **Saltar cálculos caros de fora do React**
+ * Por exemplo, chamar `expensivelyProcessAReallyLargeArrayOfObjects()` dentro do seu componente ou hook que precisa desses dados
-#### Optimizing Re-renders {/*optimizing-re-renders*/}
+#### Otimizar Re-renderizações {/*optimizing-re-renders*/}
-React lets you express your UI as a function of their current state (more concretely: their props, state, and context). In its current implementation, when a component's state changes, React will re-render that component _and all of its children_ — unless you have applied some form of manual memoization with `useMemo()`, `useCallback()`, or `React.memo()`. For example, in the following example, `` will re-render whenever ``'s state changes:
+O React permite-lhe expressar a sua UI como uma função do seu estado atual (mais concretamente: as suas props, estado, e contexto). Na sua implementação atual, quando o estado de um componente muda, o React re-renderizará esse componente _e todos os seus filhos_ — a menos que tenha aplicado alguma forma de memorização manual com `useMemo()`, `useCallback()`, ou `React.memo()`. Por exemplo, no seguinte exemplo, `` re-renderizará sempre que o estado de `` mudar:
```javascript
function FriendList({ friends }) {
@@ -81,67 +86,100 @@ function FriendList({ friends }) {
);
}
```
-[_See this example in the React Compiler Playground_](https://playground.react.dev/#N4Igzg9grgTgxgUxALhAMygOzgFwJYSYAEAYjHgpgCYAyeYOAFMEWuZVWEQL4CURwADrEicQgyKEANnkwIAwtEw4iAXiJQwCMhWoB5TDLmKsTXgG5hRInjRFGbXZwB0UygHMcACzWr1ABn4hEWsYBBxYYgAeADkIHQ4uAHoAPksRbisiMIiYYkYs6yiqPAA3FMLrIiiwAAcAQ0wU4GlZBSUcbklDNqikusaKkKrgR0TnAFt62sYHdmp+VRT7SqrqhOo6Bnl6mCoiAGsEAE9VUfmqZzwqLrHqM7ubolTVol5eTOGigFkEMDB6u4EAAhKA4HCEZ5DNZ9ErlLIWYTcEDcIA)
+[_Ver este exemplo no React Compiler Playground_](https://playground.react.dev/#N4Igzg9grgTgxgUxALhAMygOzgFwJYSYAEAYjHgpgCYAyeYOAFMEWuZVWEQL4CURwADrEicQgyKEANnkwIAwtEw4iAXiJQwCMhWoB5TDLmKsTXgG5hRInjRFGbXZwB0UygHMcACzWr1ABn4hEWsYBBxYYgAeADkIHQ4uAHoAPksRbisiMIiYYkYs6yiqPAA3FMLrIiiwAAcAQ0wU4GlZBSUcbklDNqikusaKkKrgR0TnAFt62sYHdmp+VRT7SqrqhOo6Bnl6mCoiAGsEAE9VUfmqZzwqLrHqM7ubolTVol5eTOGigFkEMDB6u4EAAhKA4HCEZ5DNZ9ErlLIWYTcEDcIA)
-React Compiler automatically applies the equivalent of manual memoization, ensuring that only the relevant parts of an app re-render as state changes, which is sometimes referred to as "fine-grained reactivity". In the above example, React Compiler determines that the return value of `` can be reused even as `friends` changes, and can avoid recreating this JSX _and_ avoid re-rendering `` as the count changes.
+O React Compiler aplica automaticamente o equivalente à memorização manual, garantindo que apenas as partes relevantes de uma aplicação se re-renderizam quando o estado muda, que às vezes é referido como "reatividade de grão fino". No exemplo acima, o React Compiler determina que o valor de retorno de `` pode ser reutilizado mesmo quando `friends` muda, e pode evitar recriar este JSX _e_ evitar re-renderizar `` quando a contagem muda.
-#### Expensive calculations also get memoized {/*expensive-calculations-also-get-memoized*/}
+#### Cálculos caros também são memorizados {/*expensive-calculations-also-get-memoized*/}
-The compiler can also automatically memoize for expensive calculations used during rendering:
+O compilador também pode memorizar automaticamente cálculos caros usados durante a renderização:
```js
-// **Not** memoized by React Compiler, since this is not a component or hook
+// **Não** memorizado pelo React Compiler, já que isto não é um componente ou hook
function expensivelyProcessAReallyLargeArrayOfObjects() { /* ... */ }
-// Memoized by React Compiler since this is a component
+// Memorizado pelo React Compiler já que isto é um componente
function TableContainer({ items }) {
- // This function call would be memoized:
+ // Esta chamada de função seria memorizada:
const data = expensivelyProcessAReallyLargeArrayOfObjects(items);
// ...
}
```
-[_See this example in the React Compiler Playground_](https://playground.react.dev/#N4Igzg9grgTgxgUxALhAejQAgFTYHIQAuumAtgqRAJYBeCAJpgEYCemASggIZyGYDCEUgAcqAGwQwANJjBUAdokyEAFlTCZ1meUUxdMcIcIjyE8vhBiYVECAGsAOvIBmURYSonMCAB7CzcgBuCGIsAAowEIhgYACCnFxioQAyXDAA5gixMDBcLADyzvlMAFYIvGAAFACUmMCYaNiYAHStOFgAvk5OGJgAshTUdIysHNy8AkbikrIKSqpaWvqGIiZmhE6u7p7ymAAqXEwSguZcCpKV9VSEFBodtcBOmAYmYHz0XIT6ALzefgFUYKhCJRBAxeLcJIsVIZLI5PKFYplCqVa63aoAbm6u0wMAQhFguwAPPRAQA+YAfL4dIloUmBMlODogDpAA)
+[_Ver este exemplo no React Compiler Playground_](https://playground.react.dev/#N4Igzg9grgTgxgUxALhAejQAgFTYHIQAuumAtgqRAJYBeCAJpgEYCemASggIZyGYDCEUgAcqAGwQwANJjBUAdokyEAFlTCZ1meUUxdMcIcIjyE8vhBiYVECAGsAOvIBmURYSonMCAB7CzcgBuCGIsAAowEIhgYACCnFxioQAyXDAA5gixMDBcLADyzvlMAFYIvGAAFACUmMCYaNiYAHStOFgAvk5OGJgAshTUdIysHNy8AkbikrIKSqpaWvqGIiZmhE6u7p7ymAAqXEwSguZcCpKV9VSEFBodtcBOmAYmYHz0XIT6ALzefgFUYKhCJRBAxeLcJIsVIZLI5PKFYplCqVa63aoAbm6u0wMAQhFguwAPPRAQA+YAfL4dIloUmBMlODogDpAA)
-However, if `expensivelyProcessAReallyLargeArrayOfObjects` is truly an expensive function, you may want to consider implementing its own memoization outside of React, because:
+No entanto, se `expensivelyProcessAReallyLargeArrayOfObjects` é verdadeiramente uma função cara, pode querer considerar implementar a sua própria memorização fora do React, porque:
-- React Compiler only memoizes React components and hooks, not every function
-- React Compiler's memoization is not shared across multiple components or hooks
+- O React Compiler apenas memoriza componentes React e hooks, não todas as funções
+- A memorização do React Compiler não é partilhada entre vários componentes ou hooks
-So if `expensivelyProcessAReallyLargeArrayOfObjects` was used in many different components, even if the same exact items were passed down, that expensive calculation would be run repeatedly. We recommend [profiling](https://react.dev/reference/react/useMemo#how-to-tell-if-a-calculation-is-expensive) first to see if it really is that expensive before making code more complicated.
+Então se `expensivelyProcessAReallyLargeArrayOfObjects` fosse usado em muitos componentes diferentes, mesmo que os mesmos itens exatos fossem passados, esse cálculo caro seria executado repetidamente. Recomendamos [fazer profiling](https://react.dev/reference/react/useMemo#how-to-tell-if-a-calculation-is-expensive) primeiro para ver se é realmente tão caro antes de tornar o código mais complicado.
-### Should I try out the compiler? {/*should-i-try-out-the-compiler*/}
+### Devo experimentar o compilador? {/*should-i-try-out-the-compiler*/}
+
+
+Por favor note que o compilador ainda está em Beta e tem muitas arestas por limar. Embora tenha sido usado em produção em empresas como a Meta, implementar o compilador em produção para a sua aplicação dependerá da saúde da sua base de código e de quão bem seguiu as [Regras do React](/reference/rules).
+
-The compiler is now in RC and has been tested extensively in production. While it has been used in production at companies like Meta, rolling out the compiler to production for your app will depend on the health of your codebase and how well you've followed the [Rules of React](/reference/rules).
+**Não tem de se apressar a usar o compilador agora. Está bem esperar até que chegue a uma versão estável antes de o adotar.** No entanto, apreciamos que o experimente em pequenas experiências nas suas aplicações para que possa [fornecer feedback](#reporting-issues) para nos ajudar a tornar o compilador melhor.
-**You don't have to rush into using the compiler now. It's okay to wait until it reaches a stable release before adopting it.** However, we do appreciate trying it out in small experiments in your apps so that you can [provide feedback](#reporting-issues) to us to help make the compiler better.
+## Primeiros Passos {/*getting-started*/}
-## Getting Started {/*getting-started*/}
+Além desta documentação, recomendamos verificar o [React Compiler Working Group](https://github.com/reactwg/react-compiler) para informação adicional e discussão sobre o compilador.
-In addition to these docs, we recommend checking the [React Compiler Working Group](https://github.com/reactwg/react-compiler) for additional information and discussion about the compiler.
-### Installing eslint-plugin-react-hooks {/*installing-eslint-plugin-react-compiler*/}
+### Instalar eslint-plugin-react-compiler {/*installing-eslint-plugin-react-compiler*/}
+
+O React Compiler também alimenta um plugin ESLint. O plugin ESLint pode ser usado **independentemente** do compilador, significando que pode usar o plugin ESLint mesmo que não use o compilador.
-React Compiler also powers an ESLint plugin. You can try it out by installing eslint-plugin-react-hooks@^6.0.0-rc.1.
{`npm install -D eslint-plugin-react-hooks@^6.0.0-rc.1`}
-See our [editor setup](/learn/editor-setup#linting) guide for more details.
-The ESLint plugin will display any violations of the rules of React in your editor. When it does this, it means that the compiler has skipped over optimizing that component or hook. This is perfectly okay, and the compiler can recover and continue optimizing other components in your codebase.
+Depois, adicione-o à sua configuração ESLint:
+
+```js
+import reactCompiler from 'eslint-plugin-react-compiler'
+
+export default [
+ {
+ plugins: {
+ 'react-compiler': reactCompiler,
+ },
+ rules: {
+ 'react-compiler/react-compiler': 'error',
+ },
+ },
+]
+```
+
+Ou, no formato de configuração eslintrc obsoleto:
+
+```js
+module.exports = {
+ plugins: [
+ 'eslint-plugin-react-compiler',
+ ],
+ rules: {
+ 'react-compiler/react-compiler': 'error',
+ },
+}
+```
+
+O plugin ESLint mostrará quaisquer violações das regras do React no seu editor. Quando isso acontece, significa que o compilador saltou a otimização desse componente ou hook. Isto está perfeitamente bem, e o compilador pode recuperar e continuar a otimizar outros componentes na sua base de código.
-**You don't have to fix all ESLint violations straight away.** You can address them at your own pace to increase the amount of components and hooks being optimized, but it is not required to fix everything before you can use the compiler.
+**Não tem de corrigir todas as violações ESLint imediatamente.** Pode abordá-las ao seu próprio ritmo para aumentar a quantidade de componentes e hooks sendo otimizados, mas não é necessário corrigir tudo antes de poder usar o compilador.
-### Rolling out the compiler to your codebase {/*using-the-compiler-effectively*/}
+### Implementar o compilador na sua base de código {/*using-the-compiler-effectively*/}
-#### Existing projects {/*existing-projects*/}
-The compiler is designed to compile functional components and hooks that follow the [Rules of React](/reference/rules). It can also handle code that breaks those rules by bailing out (skipping over) those components or hooks. However, due to the flexible nature of JavaScript, the compiler cannot catch every possible violation and may compile with false negatives: that is, the compiler may accidentally compile a component/hook that breaks the Rules of React which can lead to undefined behavior.
+#### Projetos existentes {/*existing-projects*/}
+O compilador foi desenhado para compilar componentes funcionais e hooks que seguem as [Regras do React](/reference/rules). Também pode lidar com código que quebra essas regras ao optar por sair (saltar) desses componentes ou hooks. No entanto, devido à natureza flexível do JavaScript, o compilador não pode capturar todas as possíveis violações e pode compilar com falsos negativos: isto é, o compilador pode acidentalmente compilar um componente/hook que quebra as Regras do React, o que pode levar a comportamento indefinido.
-For this reason, to adopt the compiler successfully on existing projects, we recommend running it on a small directory in your product code first. You can do this by configuring the compiler to only run on a specific set of directories:
+Por esta razão, para adotar o compilador com sucesso em projetos existentes, recomendamos executá-lo primeiro numa pequena diretoria no seu código de produto. Pode fazer isto configurando o compilador para apenas executar num conjunto específico de diretorias:
```js {3}
const ReactCompilerConfig = {
@@ -151,21 +189,21 @@ const ReactCompilerConfig = {
};
```
-When you have more confidence with rolling out the compiler, you can expand coverage to other directories as well and slowly roll it out to your whole app.
+Quando tiver mais confiança em implementar o compilador, pode expandir a cobertura para outras diretorias também e lentamente implementá-lo em toda a sua aplicação.
-#### New projects {/*new-projects*/}
+#### Novos projetos {/*new-projects*/}
-If you're starting a new project, you can enable the compiler on your entire codebase, which is the default behavior.
+Se estiver a começar um novo projeto, pode ativar o compilador em toda a sua base de código, que é o comportamento padrão.
-### Using React Compiler with React 17 or 18 {/*using-react-compiler-with-react-17-or-18*/}
+### Usar React Compiler com React 17 ou 18 {/*using-react-compiler-with-react-17-or-18*/}
-React Compiler works best with React 19 RC. If you are unable to upgrade, you can install the extra `react-compiler-runtime` package which will allow the compiled code to run on versions prior to 19. However, note that the minimum supported version is 17.
+O React Compiler funciona melhor com React 19 RC. Se não conseguir atualizar, pode instalar o pacote extra `react-compiler-runtime` que permitirá que o código compilado execute em versões anteriores à 19. No entanto, note que a versão mínima suportada é a 17.
{`npm install react-compiler-runtime@rc`}
-You should also add the correct `target` to your compiler config, where `target` is the major version of React you are targeting:
+Também deve adicionar o `target` correto à sua configuração do compilador, onde `target` é a versão principal do React que está a usar:
```js {3}
// babel.config.js
@@ -182,17 +220,17 @@ module.exports = function () {
};
```
-### Using the compiler on libraries {/*using-the-compiler-on-libraries*/}
+### Usar o compilador em bibliotecas {/*using-the-compiler-on-libraries*/}
-React Compiler can also be used to compile libraries. Because React Compiler needs to run on the original source code prior to any code transformations, it is not possible for an application's build pipeline to compile the libraries they use. Hence, our recommendation is for library maintainers to independently compile and test their libraries with the compiler, and ship compiled code to npm.
+O React Compiler também pode ser usado para compilar bibliotecas. Como o React Compiler precisa de executar no código fonte original antes de quaisquer transformações de código, não é possível para o pipeline de compilação de uma aplicação compilar as bibliotecas que usa. Portanto, a nossa recomendação é que os mantenedores de bibliotecas compiem e testem independentemente as suas bibliotecas com o compilador, e enviem código compilado para npm.
-Because your code is pre-compiled, users of your library will not need to have the compiler enabled in order to benefit from the automatic memoization applied to your library. If your library targets apps not yet on React 19, specify a minimum [`target` and add `react-compiler-runtime` as a direct dependency](#using-react-compiler-with-react-17-or-18). The runtime package will use the correct implementation of APIs depending on the application's version, and polyfill the missing APIs if necessary.
+Como o seu código está pré-compilado, os utilizadores da sua biblioteca não precisarão de ter o compilador ativado para beneficiar da memorização automática aplicada à sua biblioteca. Se a sua biblioteca é destinada a aplicações que ainda não estão no React 19, especifique um [`target` mínimo e adicione `react-compiler-runtime` como dependência direta](#using-react-compiler-with-react-17-or-18). O pacote runtime usará a implementação correta das APIs dependendo da versão da aplicação, e preencherá as APIs em falta se necessário.
-Library code can often require more complex patterns and usage of escape hatches. For this reason, we recommend ensuring that you have sufficient testing in order to identify any issues that might arise from using the compiler on your library. If you identify any issues, you can always opt-out the specific components or hooks with the [`'use no memo'` directive](#something-is-not-working-after-compilation).
+O código de bibliotecas pode frequentemente requerer padrões mais complexos e uso de escape hatches. Por esta razão, recomendamos garantir que tem testes suficientes para identificar quaisquer problemas que possam surgir do uso do compilador na sua biblioteca. Se identificar quaisquer problemas, pode sempre optar por sair de componentes ou hooks específicos com a [diretiva `'use no memo'`](#something-is-not-working-after-compilation).
-Similarly to apps, it is not necessary to fully compile 100% of your components or hooks to see benefits in your library. A good starting point might be to identify the most performance sensitive parts of your library and ensuring that they don't break the [Rules of React](/reference/rules), which you can use `eslint-plugin-react-compiler` to identify.
+Similarmente às aplicações, não é necessário compilar completamente 100% dos seus componentes ou hooks para ver benefícios na sua biblioteca. Um bom ponto de partida pode ser identificar as partes mais sensíveis ao desempenho da sua biblioteca e garantir que não quebram as [Regras do React](/reference/rules), que pode usar `eslint-plugin-react-compiler` para identificar.
-## Usage {/*installation*/}
+## Uso {/*installation*/}
### Babel {/*usage-with-babel*/}
@@ -200,9 +238,9 @@ Similarly to apps, it is not necessary to fully compile 100% of your components
{`npm install babel-plugin-react-compiler@rc`}
-The compiler includes a Babel plugin which you can use in your build pipeline to run the compiler.
+O compilador inclui um plugin Babel que pode usar no seu pipeline de compilação para executar o compilador.
-After installing, add it to your Babel config. Please note that it's critical that the compiler run **first** in the pipeline:
+Após instalar, adicione-o à sua configuração Babel. Por favor note que é crítico que o compilador execute **primeiro** no pipeline:
```js {7}
// babel.config.js
@@ -211,18 +249,18 @@ const ReactCompilerConfig = { /* ... */ };
module.exports = function () {
return {
plugins: [
- ['babel-plugin-react-compiler', ReactCompilerConfig], // must run first!
+ ['babel-plugin-react-compiler', ReactCompilerConfig], // deve executar primeiro!
// ...
],
};
};
```
-`babel-plugin-react-compiler` should run first before other Babel plugins as the compiler requires the input source information for sound analysis.
+`babel-plugin-react-compiler` deve executar primeiro antes de outros plugins Babel, já que o compilador requer a informação do código fonte de entrada para análise sólida.
### Vite {/*usage-with-vite*/}
-If you use Vite, you can add the plugin to vite-plugin-react:
+Se usar Vite, pode adicionar o plugin ao vite-plugin-react:
```js {10}
// vite.config.js
@@ -246,10 +284,10 @@ export default defineConfig(() => {
### Next.js {/*usage-with-nextjs*/}
-Please refer to the [Next.js docs](https://nextjs.org/docs/app/api-reference/next-config-js/reactCompiler) for more information.
+Por favor consulte a [documentação Next.js](https://nextjs.org/docs/app/api-reference/next-config-js/reactCompiler) para mais informação.
### Remix {/*usage-with-remix*/}
-Install `vite-plugin-babel`, and add the compiler's Babel plugin to it:
+Instale `vite-plugin-babel`, e adicione o plugin Babel do compilador a ele:
{`npm install vite-plugin-babel`}
@@ -267,7 +305,7 @@ export default defineConfig({
babel({
filter: /\.[jt]sx?$/,
babelConfig: {
- presets: ["@babel/preset-typescript"], // if you use TypeScript
+ presets: ["@babel/preset-typescript"], // se usar TypeScript
plugins: [
["babel-plugin-react-compiler", ReactCompilerConfig],
],
@@ -279,54 +317,54 @@ export default defineConfig({
### Webpack {/*usage-with-webpack*/}
-A community webpack loader is [now available here](https://github.com/SukkaW/react-compiler-webpack).
+Um loader webpack da comunidade está [agora disponível aqui](https://github.com/SukkaW/react-compiler-webpack).
### Expo {/*usage-with-expo*/}
-Please refer to [Expo's docs](https://docs.expo.dev/guides/react-compiler/) to enable and use the React Compiler in Expo apps.
+Por favor consulte a [documentação Expo](https://docs.expo.dev/guides/react-compiler/) para ativar e usar o React Compiler em aplicações Expo.
### Metro (React Native) {/*usage-with-react-native-metro*/}
-React Native uses Babel via Metro, so refer to the [Usage with Babel](#usage-with-babel) section for installation instructions.
+React Native usa Babel via Metro, então consulte a secção [Uso com Babel](#usage-with-babel) para instruções de instalação.
### Rspack {/*usage-with-rspack*/}
-Please refer to [Rspack's docs](https://rspack.dev/guide/tech/react#react-compiler) to enable and use the React Compiler in Rspack apps.
+Por favor consulte a [documentação Rspack](https://rspack.dev/guide/tech/react#react-compiler) para ativar e usar o React Compiler em aplicações Rspack.
### Rsbuild {/*usage-with-rsbuild*/}
-Please refer to [Rsbuild's docs](https://rsbuild.dev/guide/framework/react#react-compiler) to enable and use the React Compiler in Rsbuild apps.
+Por favor consulte a [documentação Rsbuild](https://rsbuild.dev/guide/framework/react#react-compiler) para ativar e usar o React Compiler em aplicações Rsbuild.
-## Troubleshooting {/*troubleshooting*/}
+## Resolução de Problemas {/*troubleshooting*/}
-To report issues, please first create a minimal repro on the [React Compiler Playground](https://playground.react.dev/) and include it in your bug report. You can open issues in the [facebook/react](https://github.com/facebook/react/issues) repo.
+Para reportar problemas, por favor primeiro crie uma reprodução mínima no [React Compiler Playground](https://playground.react.dev/) e inclua-a no seu relatório de bug. Pode abrir issues no repositório [facebook/react](https://github.com/facebook/react/issues).
-You can also provide feedback in the React Compiler Working Group by applying to be a member. Please see [the README for more details on joining](https://github.com/reactwg/react-compiler).
+Também pode fornecer feedback no React Compiler Working Group candidatando-se a ser membro. Por favor veja [o README para mais detalhes sobre como se juntar](https://github.com/reactwg/react-compiler).
-### What does the compiler assume? {/*what-does-the-compiler-assume*/}
+### O que assume o compilador? {/*what-does-the-compiler-assume*/}
-React Compiler assumes that your code:
+O React Compiler assume que o seu código:
-1. Is valid, semantic JavaScript.
-2. Tests that nullable/optional values and properties are defined before accessing them (for example, by enabling [`strictNullChecks`](https://www.typescriptlang.org/tsconfig/#strictNullChecks) if using TypeScript), i.e., `if (object.nullableProperty) { object.nullableProperty.foo }` or with optional-chaining `object.nullableProperty?.foo`.
-3. Follows the [Rules of React](https://react.dev/reference/rules).
+1. É JavaScript válido e semântico.
+2. Testa que valores e propriedades nullable/opcionais estão definidos antes de os aceder (por exemplo, ativando [`strictNullChecks`](https://www.typescriptlang.org/tsconfig/#strictNullChecks) se usar TypeScript), i.e., `if (object.nullableProperty) { object.nullableProperty.foo }` ou com optional-chaining `object.nullableProperty?.foo`.
+3. Segue as [Regras do React](https://react.dev/reference/rules).
-React Compiler can verify many of the Rules of React statically, and will safely skip compilation when it detects an error. To see the errors we recommend also installing [eslint-plugin-react-compiler](https://www.npmjs.com/package/eslint-plugin-react-compiler).
+O React Compiler pode verificar muitas das Regras do React estaticamente, e saltará com segurança a compilação quando detetar um erro. Para ver os erros recomendamos também instalar [eslint-plugin-react-compiler](https://www.npmjs.com/package/eslint-plugin-react-compiler).
-### How do I know my components have been optimized? {/*how-do-i-know-my-components-have-been-optimized*/}
+### Como sei que os meus componentes foram otimizados? {/*how-do-i-know-my-components-have-been-optimized*/}
-[React DevTools](/learn/react-developer-tools) (v5.0+) and [React Native DevTools](https://reactnative.dev/docs/react-native-devtools) have built-in support for React Compiler and will display a "Memo ✨" badge next to components that have been optimized by the compiler.
+[React DevTools](/learn/react-developer-tools) (v5.0+) e [React Native DevTools](https://reactnative.dev/docs/react-native-devtools) têm suporte integrado para React Compiler e mostrarão um badge "Memo ✨" ao lado de componentes que foram otimizados pelo compilador.
-### Something is not working after compilation {/*something-is-not-working-after-compilation*/}
-If you have eslint-plugin-react-compiler installed, the compiler will display any violations of the rules of React in your editor. When it does this, it means that the compiler has skipped over optimizing that component or hook. This is perfectly okay, and the compiler can recover and continue optimizing other components in your codebase. **You don't have to fix all ESLint violations straight away.** You can address them at your own pace to increase the amount of components and hooks being optimized.
+### Algo não está a funcionar após a compilação {/*something-is-not-working-after-compilation*/}
+Se tiver eslint-plugin-react-compiler instalado, o compilador mostrará quaisquer violações das regras do React no seu editor. Quando isso acontece, significa que o compilador saltou a otimização desse componente ou hook. Isto está perfeitamente bem, e o compilador pode recuperar e continuar a otimizar outros componentes na sua base de código. **Não tem de corrigir todas as violações ESLint imediatamente.** Pode abordá-las ao seu próprio ritmo para aumentar a quantidade de componentes e hooks sendo otimizados.
-Due to the flexible and dynamic nature of JavaScript however, it's not possible to comprehensively detect all cases. Bugs and undefined behavior such as infinite loops may occur in those cases.
+Devido à natureza flexível e dinâmica do JavaScript no entanto, não é possível detetar de forma abrangente todos os casos. Bugs e comportamento indefinido como loops infinitos podem ocorrer nesses casos.
-If your app doesn't work properly after compilation and you aren't seeing any ESLint errors, the compiler may be incorrectly compiling your code. To confirm this, try to make the issue go away by aggressively opting out any component or hook you think might be related via the [`"use no memo"` directive](#opt-out-of-the-compiler-for-a-component).
+Se a sua aplicação não funciona corretamente após a compilação e não vê quaisquer erros ESLint, o compilador pode estar a compilar incorretamente o seu código. Para confirmar isto, tente fazer o problema desaparecer optando agressivamente por sair de qualquer componente ou hook que pense que possa estar relacionado via a [diretiva `"use no memo"`](#opt-out-of-the-compiler-for-a-component).
```js {2}
function SuspiciousComponent() {
- "use no memo"; // opts out this component from being compiled by React Compiler
+ "use no memo"; // opta este componente por sair de ser compilado pelo React Compiler
// ...
}
```
@@ -334,13 +372,13 @@ function SuspiciousComponent() {
#### `"use no memo"` {/*use-no-memo*/}
-`"use no memo"` is a _temporary_ escape hatch that lets you opt-out components and hooks from being compiled by the React Compiler. This directive is not meant to be long lived the same way as eg [`"use client"`](/reference/rsc/use-client) is.
+`"use no memo"` é um escape hatch _temporário_ que permite optar por sair componentes e hooks de serem compilados pelo React Compiler. Esta diretiva não se destina a ser duradoura da mesma forma que p.ex. [`"use client"`](/reference/rsc/use-client) é.
-It is not recommended to reach for this directive unless it's strictly necessary. Once you opt-out a component or hook, it is opted-out forever until the directive is removed. This means that even if you fix the code, the compiler will still skip over compiling it unless you remove the directive.
+Não é recomendado recorrer a esta diretiva a menos que seja estritamente necessário. Uma vez que opta por sair de um componente ou hook, está optado por sair para sempre até que a diretiva seja removida. Isto significa que mesmo que corrija o código, o compilador ainda saltará a compilação dele a menos que remova a diretiva.
-When you make the error go away, confirm that removing the opt out directive makes the issue come back. Then share a bug report with us (you can try to reduce it to a small repro, or if it's open source code you can also just paste the entire source) using the [React Compiler Playground](https://playground.react.dev) so we can identify and help fix the issue.
+Quando fizer o erro desaparecer, confirme que remover a diretiva de opt out faz o problema voltar. Depois partilhe um relatório de bug connosco (pode tentar reduzi-lo a uma pequena reprodução, ou se for código de código aberto também pode apenas colar todo o código fonte) usando o [React Compiler Playground](https://playground.react.dev) para que possamos identificar e ajudar a corrigir o problema.
-### Other issues {/*other-issues*/}
+### Outros problemas {/*other-issues*/}
-Please see https://github.com/reactwg/react-compiler/discussions/7.
+Por favor veja https://github.com/reactwg/react-compiler/discussions/7.
\ No newline at end of file
diff --git a/src/content/learn/setup.md b/src/content/learn/setup.md
index 2c46ee148..2ef410686 100644
--- a/src/content/learn/setup.md
+++ b/src/content/learn/setup.md
@@ -1,28 +1,28 @@
---
-title: Setup
+title: Configuração
---
-React integrates with tools like editors, TypeScript, browser extensions, and compilers. This section will help you get your environment set up.
+O React se integra com ferramentas como editores, TypeScript, extensões de navegador e compiladores. Esta seção vai te ajudar a configurar seu ambiente.
-## Editor Setup {/*editor-setup*/}
+## Configuração do Editor {/*editor-setup*/}
-See our [recommended editors](/learn/editor-setup) and learn how to set them up to work with React.
+Veja nossos [editores recomendados](/learn/editor-setup) e aprenda como configurá-los para trabalhar com o React.
-## Using TypeScript {/*using-typescript*/}
+## Usando TypeScript {/*using-typescript*/}
-TypeScript is a popular way to add type definitions to JavaScript codebases. [Learn how to integrate TypeScript into your React projects](/learn/typescript).
+TypeScript é uma forma popular de adicionar definições de tipos a bases de código JavaScript. [Aprenda como integrar o TypeScript aos seus projetos React](/learn/typescript).
-## React Developer Tools {/*react-developer-tools*/}
+## Ferramentas de Desenvolvedor React {/*react-developer-tools*/}
-React Developer Tools is a browser extension that can inspect React components, edit props and state, and identify performance problems. Learn how to install it [here](learn/react-developer-tools).
+As Ferramentas de Desenvolvedor React são uma extensão de navegador que pode inspecionar componentes React, editar props e estado, e identificar problemas de performance. Aprenda como instalá-las [aqui](learn/react-developer-tools).
-## React Compiler {/*react-compiler*/}
+## Compilador React {/*react-compiler*/}
-React Compiler is a tool that automatically optimizes your React app. [Learn more](/learn/react-compiler).
+O Compilador React é uma ferramenta que otimiza automaticamente seu app React. [Saiba mais](/learn/react-compiler).
-## Next steps {/*next-steps*/}
+## Próximos passos {/*next-steps*/}
-Head to the [Quick Start](/learn) guide for a tour of the most important React concepts you will encounter every day.
+Acesse o guia [Início Rápido](/learn) para um tour pelos conceitos mais importantes do React que você encontrará todos os dias.
diff --git a/src/content/learn/thinking-in-react.md b/src/content/learn/thinking-in-react.md
index 822891e60..99d47a6ca 100644
--- a/src/content/learn/thinking-in-react.md
+++ b/src/content/learn/thinking-in-react.md
@@ -1,18 +1,18 @@
---
-title: Thinking in React
+title: Pensando em React
---
-React can change how you think about the designs you look at and the apps you build. When you build a user interface with React, you will first break it apart into pieces called *components*. Then, you will describe the different visual states for each of your components. Finally, you will connect your components together so that the data flows through them. In this tutorial, we’ll guide you through the thought process of building a searchable product data table with React.
+O React pode mudar a forma como você pensa sobre os designs que observa e as aplicações que constrói. Quando você constrói uma interface de usuário com React, primeiro você a dividirá em partes chamadas *componentes*. Em seguida, você descreverá os diferentes estados visuais para cada um dos seus componentes. Finalmente, você conectará seus componentes para que os dados fluam através deles. Neste tutorial, nós o guiaremos através do processo de pensamento de construir uma tabela de dados de produtos pesquisável com React.
-## Start with the mockup {/*start-with-the-mockup*/}
+## Comece com o mockup {/*start-with-the-mockup*/}
-Imagine that you already have a JSON API and a mockup from a designer.
+Imagine que você já tem uma API JSON e um mockup de um designer.
-The JSON API returns some data that looks like this:
+A API JSON retorna alguns dados que se parecem com isto:
```json
[
@@ -25,25 +25,25 @@ The JSON API returns some data that looks like this:
]
```
-The mockup looks like this:
+O mockup se parece com isto:
-To implement a UI in React, you will usually follow the same five steps.
+Para implementar uma UI em React, você geralmente seguirá os mesmos cinco passos.
-## Step 1: Break the UI into a component hierarchy {/*step-1-break-the-ui-into-a-component-hierarchy*/}
+## Passo 1: Divida a UI em uma hierarquia de componentes {/*step-1-break-the-ui-into-a-component-hierarchy*/}
-Start by drawing boxes around every component and subcomponent in the mockup and naming them. If you work with a designer, they may have already named these components in their design tool. Ask them!
+Comece desenhando caixas ao redor de cada componente e subcomponente no mockup e nomeando-os. Se você trabalha com um designer, eles podem já ter nomeado esses componentes em sua ferramenta de design. Pergunte a eles!
-Depending on your background, you can think about splitting up a design into components in different ways:
+Dependendo do seu background, você pode pensar sobre dividir um design em componentes de diferentes maneiras:
-* **Programming**--use the same techniques for deciding if you should create a new function or object. One such technique is the [single responsibility principle](https://en.wikipedia.org/wiki/Single_responsibility_principle), that is, a component should ideally only do one thing. If it ends up growing, it should be decomposed into smaller subcomponents.
-* **CSS**--consider what you would make class selectors for. (However, components are a bit less granular.)
-* **Design**--consider how you would organize the design's layers.
+* **Programação**--use as mesmas técnicas para decidir se você deve criar uma nova função ou objeto. Uma dessas técnicas é o [princípio da responsabilidade única](https://en.wikipedia.org/wiki/Single_responsibility_principle), ou seja, um componente deve idealmente fazer apenas uma coisa. Se ele acabar crescendo, deve ser decomposto em subcomponentes menores.
+* **CSS**--considere para o que você faria seletores de classe. (No entanto, os componentes são um pouco menos granulares.)
+* **Design**--considere como você organizaria as camadas do design.
-If your JSON is well-structured, you'll often find that it naturally maps to the component structure of your UI. That's because UI and data models often have the same information architecture--that is, the same shape. Separate your UI into components, where each component matches one piece of your data model.
+Se seu JSON está bem estruturado, você frequentemente descobrirá que ele mapeia naturalmente para a estrutura de componentes de sua UI. Isso ocorre porque UI e modelos de dados frequentemente têm a mesma arquitetura de informação--ou seja, a mesma forma. Separe sua UI em componentes, onde cada componente corresponde a uma parte do seu modelo de dados.
-There are five components on this screen:
+Há cinco componentes nesta tela:
@@ -51,19 +51,19 @@ There are five components on this screen:
-1. `FilterableProductTable` (grey) contains the entire app.
-2. `SearchBar` (blue) receives the user input.
-3. `ProductTable` (lavender) displays and filters the list according to the user input.
-4. `ProductCategoryRow` (green) displays a heading for each category.
-5. `ProductRow` (yellow) displays a row for each product.
+1. `FilterableProductTable` (cinza) contém toda a aplicação.
+2. `SearchBar` (azul) recebe a entrada do usuário.
+3. `ProductTable` (lavanda) exibe e filtra a lista de acordo com a entrada do usuário.
+4. `ProductCategoryRow` (verde) exibe um cabeçalho para cada categoria.
+5. `ProductRow` (amarelo) exibe uma linha para cada produto.
-If you look at `ProductTable` (lavender), you'll see that the table header (containing the "Name" and "Price" labels) isn't its own component. This is a matter of preference, and you could go either way. For this example, it is a part of `ProductTable` because it appears inside the `ProductTable`'s list. However, if this header grows to be complex (e.g., if you add sorting), you can move it into its own `ProductTableHeader` component.
+Se você olhar para `ProductTable` (lavanda), verá que o cabeçalho da tabela (contendo os rótulos "Name" e "Price") não é seu próprio componente. Esta é uma questão de preferência, e você pode ir de qualquer forma. Para este exemplo, é parte de `ProductTable` porque aparece dentro da lista de `ProductTable`. No entanto, se este cabeçalho crescer para ser complexo (por exemplo, se você adicionar ordenação), você pode movê-lo para seu próprio componente `ProductTableHeader`.
-Now that you've identified the components in the mockup, arrange them into a hierarchy. Components that appear within another component in the mockup should appear as a child in the hierarchy:
+Agora que você identificou os componentes no mockup, organize-os em uma hierarquia. Componentes que aparecem dentro de outro componente no mockup devem aparecer como filhos na hierarquia:
* `FilterableProductTable`
* `SearchBar`
@@ -71,13 +71,13 @@ Now that you've identified the components in the mockup, arrange them into a hie
* `ProductCategoryRow`
* `ProductRow`
-## Step 2: Build a static version in React {/*step-2-build-a-static-version-in-react*/}
+## Passo 2: Construa uma versão estática em React {/*step-2-build-a-static-version-in-react*/}
-Now that you have your component hierarchy, it's time to implement your app. The most straightforward approach is to build a version that renders the UI from your data model without adding any interactivity... yet! It's often easier to build the static version first and add interactivity later. Building a static version requires a lot of typing and no thinking, but adding interactivity requires a lot of thinking and not a lot of typing.
+Agora que você tem sua hierarquia de componentes, é hora de implementar sua aplicação. A abordagem mais direta é construir uma versão que renderiza a UI a partir do seu modelo de dados sem adicionar qualquer interatividade... ainda! É frequentemente mais fácil construir a versão estática primeiro e adicionar interatividade depois. Construir uma versão estática requer muito digitação e nenhum pensamento, mas adicionar interatividade requer muito pensamento e pouca digitação.
-To build a static version of your app that renders your data model, you'll want to build [components](/learn/your-first-component) that reuse other components and pass data using [props.](/learn/passing-props-to-a-component) Props are a way of passing data from parent to child. (If you're familiar with the concept of [state](/learn/state-a-components-memory), don't use state at all to build this static version. State is reserved only for interactivity, that is, data that changes over time. Since this is a static version of the app, you don't need it.)
+Para construir uma versão estática de sua aplicação que renderiza seu modelo de dados, você vai querer construir [componentes](/learn/your-first-component) que reutilizam outros componentes e passam dados usando [props.](/learn/passing-props-to-a-component) Props são uma forma de passar dados de pai para filho. (Se você está familiarizado com o conceito de [state](/learn/state-a-components-memory), não use state de forma alguma para construir esta versão estática. State é reservado apenas para interatividade, ou seja, dados that change over time. Como esta é uma versão estática da aplicação, você não precisa dele.)
-You can either build "top down" by starting with building the components higher up in the hierarchy (like `FilterableProductTable`) or "bottom up" by working from components lower down (like `ProductRow`). In simpler examples, it’s usually easier to go top-down, and on larger projects, it’s easier to go bottom-up.
+Você pode construir "de cima para baixo" começando com a construção dos componentes mais altos na hierarquia (como `FilterableProductTable`) ou "de baixo para cima" trabalhando a partir de componentes mais baixos (como `ProductRow`). Em exemplos mais simples, é geralmente mais fácil ir de cima para baixo, e em projetos maiores, é mais fácil ir de baixo para cima.
@@ -195,85 +195,85 @@ td {
-(If this code looks intimidating, go through the [Quick Start](/learn/) first!)
+(Se este código parece intimidante, passe pelo [Início Rápido](/learn/) primeiro!)
-After building your components, you'll have a library of reusable components that render your data model. Because this is a static app, the components will only return JSX. The component at the top of the hierarchy (`FilterableProductTable`) will take your data model as a prop. This is called _one-way data flow_ because the data flows down from the top-level component to the ones at the bottom of the tree.
+Depois de construir seus componentes, você terá uma biblioteca de componentes reutilizáveis que renderizam seu modelo de dados. Como esta é uma aplicação estática, os componentes apenas retornarão JSX. O componente no topo da hierarquia (`FilterableProductTable`) receberá seu modelo de dados como prop. Isso é chamado de _fluxo de dados unidirecional_ porque os dados fluem de cima do componente de nível superior para os da parte inferior da árvore.
-At this point, you should not be using any state values. That’s for the next step!
+Neste ponto, você não deve estar usando nenhum valor de state. Isso é para o próximo passo!
-## Step 3: Find the minimal but complete representation of UI state {/*step-3-find-the-minimal-but-complete-representation-of-ui-state*/}
+## Passo 3: Encontre a representação mínima mas completa do estado da UI {/*step-3-find-the-minimal-but-complete-representation-of-ui-state*/}
-To make the UI interactive, you need to let users change your underlying data model. You will use *state* for this.
+Para tornar a UI interativa, você precisa permitir que os usuários alterem seu modelo de dados subjacente. Você usará *state* para isso.
-Think of state as the minimal set of changing data that your app needs to remember. The most important principle for structuring state is to keep it [DRY (Don't Repeat Yourself).](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself) Figure out the absolute minimal representation of the state your application needs and compute everything else on-demand. For example, if you're building a shopping list, you can store the items as an array in state. If you want to also display the number of items in the list, don't store the number of items as another state value--instead, read the length of your array.
+Pense no state como o conjunto mínimo de dados em mudança que sua aplicação precisa lembrar. O princípio mais importante para estruturar o state é mantê-lo [DRY (Don't Repeat Yourself - Não Se Repita).](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself) Descubra a representação absolutamente mínima do state que sua aplicação precisa e compute todo o resto sob demanda. Por exemplo, se você está construindo uma lista de compras, você pode armazenar os itens como um array no state. Se você também quer exibir o número de itens na lista, não armazene o número de itens como outro valor de state--em vez disso, leia o comprimento do seu array.
-Now think of all of the pieces of data in this example application:
+Agora pense em todas as partes de dados nesta aplicação de exemplo:
-1. The original list of products
-2. The search text the user has entered
-3. The value of the checkbox
-4. The filtered list of products
+1. A lista original de produtos
+2. O texto de busca que o usuário digitou
+3. O valor da checkbox
+4. A lista filtrada de produtos
-Which of these are state? Identify the ones that are not:
+Quais desses são state? Identifique os que não são:
-* Does it **remain unchanged** over time? If so, it isn't state.
-* Is it **passed in from a parent** via props? If so, it isn't state.
-* **Can you compute it** based on existing state or props in your component? If so, it *definitely* isn't state!
+* **Permanece inalterado** ao longo do tempo? Se sim, não é state.
+* É **passado de um pai** via props? Se sim, não é state.
+* **Você pode computá-lo** baseado no state ou props existentes em seu componente? Se sim, *definitivamente* não é state!
-What's left is probably state.
+O que sobra provavelmente é state.
-Let's go through them one by one again:
+Vamos passá-los um por um novamente:
-1. The original list of products is **passed in as props, so it's not state.**
-2. The search text seems to be state since it changes over time and can't be computed from anything.
-3. The value of the checkbox seems to be state since it changes over time and can't be computed from anything.
-4. The filtered list of products **isn't state because it can be computed** by taking the original list of products and filtering it according to the search text and value of the checkbox.
+1. A lista original de produtos é **passada como props, então não é state.**
+2. O texto de busca parece ser state já que muda ao longo do tempo e não pode ser computado a partir de nada.
+3. O valor da checkbox parece ser state já que muda ao longo do tempo e não pode ser computado a partir de nada.
+4. A lista filtrada de produtos **não é state porque pode ser computada** pegando a lista original de produtos e filtrando-a de acordo com o texto de busca e o valor da checkbox.
-This means only the search text and the value of the checkbox are state! Nicely done!
+Isso significa que apenas o texto de busca e o valor da checkbox são state! Muito bem!
#### Props vs State {/*props-vs-state*/}
-There are two types of "model" data in React: props and state. The two are very different:
+Há dois tipos de dados "modelo" em React: props e state. Os dois são muito diferentes:
-* [**Props** are like arguments you pass](/learn/passing-props-to-a-component) to a function. They let a parent component pass data to a child component and customize its appearance. For example, a `Form` can pass a `color` prop to a `Button`.
-* [**State** is like a component’s memory.](/learn/state-a-components-memory) It lets a component keep track of some information and change it in response to interactions. For example, a `Button` might keep track of `isHovered` state.
+* [**Props** são como argumentos que você passa](/learn/passing-props-to-a-component) para uma função. Eles permitem que um componente pai passe dados para um componente filho e personalize sua aparência. Por exemplo, um `Form` pode passar uma prop `color` para um `Button`.
+* [**State** é como a memória de um componente.](/learn/state-a-components-memory) Ele permite que um componente mantenha controle de algumas informações e as altere em resposta a interações. Por exemplo, um `Button` pode manter controle do state `isHovered`.
-Props and state are different, but they work together. A parent component will often keep some information in state (so that it can change it), and *pass it down* to child components as their props. It's okay if the difference still feels fuzzy on the first read. It takes a bit of practice for it to really stick!
+Props e state são diferentes, mas trabalham juntos. Um componente pai frequentemente manterá algumas informações no state (para que possa alterá-las), e *passá-las para baixo* para componentes filhos como suas props. É normal se a diferença ainda parecer confusa na primeira leitura. Leva um pouco de prática para realmente entender!
-## Step 4: Identify where your state should live {/*step-4-identify-where-your-state-should-live*/}
+## Passo 4: Identifique onde seu state deve viver {/*step-4-identify-where-your-state-should-live*/}
-After identifying your app’s minimal state data, you need to identify which component is responsible for changing this state, or *owns* the state. Remember: React uses one-way data flow, passing data down the component hierarchy from parent to child component. It may not be immediately clear which component should own what state. This can be challenging if you’re new to this concept, but you can figure it out by following these steps!
+Depois de identificar os dados de state mínimos da sua aplicação, você precisa identificar qual componente é responsável por alterar este state, ou *possui* o state. Lembre-se: o React usa fluxo de dados unidirecional, passando dados pela hierarquia de componentes do componente pai para o componente filho. Pode não estar imediatamente claro qual componente deve possuir qual state. Isso pode ser desafiador se você é novo neste conceito, mas você pode descobrir seguindo estes passos!
-For each piece of state in your application:
+Para cada parte do state em sua aplicação:
-1. Identify *every* component that renders something based on that state.
-2. Find their closest common parent component--a component above them all in the hierarchy.
-3. Decide where the state should live:
- 1. Often, you can put the state directly into their common parent.
- 2. You can also put the state into some component above their common parent.
- 3. If you can't find a component where it makes sense to own the state, create a new component solely for holding the state and add it somewhere in the hierarchy above the common parent component.
+1. Identifique *todos* os componentes que renderizam algo baseado naquele state.
+2. Encontre o componente pai comum mais próximo--um componente acima de todos eles na hierarquia.
+3. Decida onde o state deve viver:
+ 1. Frequentemente, você pode colocar o state diretamente no pai comum deles.
+ 2. Você também pode colocar o state em algum componente acima do pai comum deles.
+ 3. Se você não conseguir encontrar um componente onde faça sentido possuir o state, crie um novo componente apenas para manter o state e adicione-o em algum lugar na hierarquia acima do componente pai comum.
-In the previous step, you found two pieces of state in this application: the search input text, and the value of the checkbox. In this example, they always appear together, so it makes sense to put them into the same place.
+No passo anterior, você encontrou duas partes de state nesta aplicação: o texto de entrada de busca, e o valor da checkbox. Neste exemplo, eles sempre aparecem juntos, então faz sentido colocá-los no mesmo lugar.
-Now let's run through our strategy for them:
+Agora vamos executar nossa estratégia para eles:
-1. **Identify components that use state:**
- * `ProductTable` needs to filter the product list based on that state (search text and checkbox value).
- * `SearchBar` needs to display that state (search text and checkbox value).
-2. **Find their common parent:** The first parent component both components share is `FilterableProductTable`.
-3. **Decide where the state lives**: We'll keep the filter text and checked state values in `FilterableProductTable`.
+1. **Identifique componentes que usam state:**
+ * `ProductTable` precisa filtrar a lista de produtos baseada naquele state (texto de busca e valor da checkbox).
+ * `SearchBar` precisa exibir aquele state (texto de busca e valor da checkbox).
+2. **Encontre o pai comum:** O primeiro componente pai que ambos os componentes compartilham é `FilterableProductTable`.
+3. **Decida onde o state vive**: Vamos manter os valores de texto de filtro e estado marcado em `FilterableProductTable`.
-So the state values will live in `FilterableProductTable`.
+Então os valores de state viverão em `FilterableProductTable`.
-Add state to the component with the [`useState()` Hook.](/reference/react/useState) Hooks are special functions that let you "hook into" React. Add two state variables at the top of `FilterableProductTable` and specify their initial state:
+Adicione state ao componente com o [`useState()` Hook.](/reference/react/useState) Hooks são funções especiais que permitem que você "se conecte" ao React. Adicione duas variáveis de state no topo de `FilterableProductTable` e especifique seu state inicial:
```js
function FilterableProductTable({ products }) {
@@ -281,7 +281,7 @@ function FilterableProductTable({ products }) {
const [inStockOnly, setInStockOnly] = useState(false);
```
-Then, pass `filterText` and `inStockOnly` to `ProductTable` and `SearchBar` as props:
+Em seguida, passe `filterText` e `inStockOnly` para `ProductTable` e `SearchBar` como props:
```js
@@ -295,7 +295,7 @@ Then, pass `filterText` and `inStockOnly` to `ProductTable` and `SearchBar` as p
```
-You can start seeing how your application will behave. Edit the `filterText` initial value from `useState('')` to `useState('fruit')` in the sandbox code below. You'll see both the search input text and the table update:
+Você pode começar a ver como sua aplicação se comportará. Edite o valor inicial de `filterText` de `useState('')` para `useState('fruit')` no código sandbox abaixo. Você verá tanto o texto de entrada de busca quanto a tabela atualizarem:
@@ -437,15 +437,15 @@ td {
-Notice that editing the form doesn't work yet. There is a console error in the sandbox above explaining why:
+Note que editar o formulário ainda não funciona. Há um erro no console no sandbox acima explicando o porquê:
-You provided a \`value\` prop to a form field without an \`onChange\` handler. This will render a read-only field.
+Você forneceu uma prop \`value\` para um campo de formulário sem um manipulador \`onChange\`. Isso renderizará um campo somente leitura.
-In the sandbox above, `ProductTable` and `SearchBar` read the `filterText` and `inStockOnly` props to render the table, the input, and the checkbox. For example, here is how `SearchBar` populates the input value:
+No sandbox acima, `ProductTable` e `SearchBar` leem as props `filterText` e `inStockOnly` para renderizar a tabela, a entrada, e a checkbox. Por exemplo, aqui está como `SearchBar` popula o valor da entrada:
```js {1,6}
function SearchBar({ filterText, inStockOnly }) {
@@ -457,16 +457,15 @@ function SearchBar({ filterText, inStockOnly }) {
placeholder="Search..."/>
```
-However, you haven't added any code to respond to the user actions like typing yet. This will be your final step.
+No entanto, você ainda não adicionou nenhum código para responder às ações do usuário como digitação. Este será seu passo final.
+## Passo 5: Adicione fluxo de dados inverso {/*step-5-add-inverse-data-flow*/}
-## Step 5: Add inverse data flow {/*step-5-add-inverse-data-flow*/}
+Atualmente sua aplicação renderiza corretamente com props e state fluindo pela hierarquia. Mas para alterar o state de acordo com a entrada do usuário, você precisará suportar dados fluindo no outro sentido: os componentes de formulário profundos na hierarquia precisam atualizar o state em `FilterableProductTable`.
-Currently your app renders correctly with props and state flowing down the hierarchy. But to change the state according to user input, you will need to support data flowing the other way: the form components deep in the hierarchy need to update the state in `FilterableProductTable`.
+O React torna este fluxo de dados explícito, mas requer um pouco mais de digitação do que vinculação de dados bidirecional. Se você tentar digitar ou marcar a caixa no exemplo acima, verá que o React ignora sua entrada. Isso é intencional. Ao escrever ``, você definiu a prop `value` do `input` para sempre ser igual ao state `filterText` passado de `FilterableProductTable`. Como o state `filterText` nunca é definido, a entrada nunca muda.
-React makes this data flow explicit, but it requires a little more typing than two-way data binding. If you try to type or check the box in the example above, you'll see that React ignores your input. This is intentional. By writing ``, you've set the `value` prop of the `input` to always be equal to the `filterText` state passed in from `FilterableProductTable`. Since `filterText` state is never set, the input never changes.
-
-You want to make it so whenever the user changes the form inputs, the state updates to reflect those changes. The state is owned by `FilterableProductTable`, so only it can call `setFilterText` and `setInStockOnly`. To let `SearchBar` update the `FilterableProductTable`'s state, you need to pass these functions down to `SearchBar`:
+Você quer fazer com que sempre que o usuário altere as entradas do formulário, o state atualize para refletir essas mudanças. O state é possuído por `FilterableProductTable`, então apenas ele pode chamar `setFilterText` e `setInStockOnly`. Para permitir que `SearchBar` atualize o state de `FilterableProductTable`, você precisa passar essas funções para `SearchBar`:
```js {2,3,10,11}
function FilterableProductTable({ products }) {
@@ -482,7 +481,7 @@ function FilterableProductTable({ products }) {
onInStockOnlyChange={setInStockOnly} />
```
-Inside the `SearchBar`, you will add the `onChange` event handlers and set the parent state from them:
+Dentro do `SearchBar`, você adicionará os manipuladores de evento `onChange` e definirá o state pai a partir deles:
```js {4,5,13,19}
function SearchBar({
@@ -506,7 +505,7 @@ function SearchBar({
onChange={(e) => onInStockOnlyChange(e.target.checked)}
```
-Now the application fully works!
+Agora a aplicação funciona completamente!
@@ -656,8 +655,8 @@ td {
-You can learn all about handling events and updating state in the [Adding Interactivity](/learn/adding-interactivity) section.
+Você pode aprender tudo sobre manipulação de eventos e atualização de state na seção [Adicionando Interatividade](/learn/adding-interactivity).
-## Where to go from here {/*where-to-go-from-here*/}
+## Para onde ir daqui {/*where-to-go-from-here*/}
-This was a very brief introduction to how to think about building components and applications with React. You can [start a React project](/learn/installation) right now or [dive deeper on all the syntax](/learn/describing-the-ui) used in this tutorial.
+Esta foi uma introdução muito breve sobre como pensar sobre construir componentes e aplicações com React. Você pode [iniciar um projeto React](/learn/installation) agora mesmo ou [mergulhar mais fundo em toda a sintaxe](/learn/describing-the-ui) usada neste tutorial.
\ No newline at end of file