diff --git a/src/content/reference/react/StrictMode.md b/src/content/reference/react/StrictMode.md index 92c6ba63a..e324a3994 100644 --- a/src/content/reference/react/StrictMode.md +++ b/src/content/reference/react/StrictMode.md @@ -5,7 +5,7 @@ title: -`` lets you find common bugs in your components early during development. +`` permite que você encontre erros comuns em seus componentes mais cedo durante o desenvolvimento. ```js @@ -20,11 +20,11 @@ title: --- -## Reference {/*reference*/} +## Referência {/*reference*/} ### `` {/*strictmode*/} -Use `StrictMode` to enable additional development behaviors and warnings for the component tree inside: +Use `StrictMode` para habilitar comportamentos e avisos adicionais de desenvolvimento para a árvore de componentes dentro: ```js import { StrictMode } from 'react'; @@ -38,32 +38,32 @@ root.render( ); ``` -[See more examples below.](#usage) +[Veja mais exemplos abaixo.](#usage) -Strict Mode enables the following development-only behaviors: +O Modo Estrito habilita os seguintes comportamentos apenas para desenvolvimento: -- Your components will [re-render an extra time](#fixing-bugs-found-by-double-rendering-in-development) to find bugs caused by impure rendering. -- Your components will [re-run Effects an extra time](#fixing-bugs-found-by-re-running-effects-in-development) to find bugs caused by missing Effect cleanup. -- Your components will [be checked for usage of deprecated APIs.](#fixing-deprecation-warnings-enabled-by-strict-mode) +- Seus componentes serão [re-renderizados uma vez a mais](#fixing-bugs-found-by-double-rendering-in-development) para encontrar erros causados por renderização impura. +- Seus componentes [re-executarão efeitos uma vez a mais](#fixing-bugs-found-by-re-running-effects-in-development) para encontrar erros causados pela ausência de limpeza de efeito. +- Seus componentes [serão verificados quanto ao uso de APIs obsoletas.](#fixing-deprecation-warnings-enabled-by-strict-mode) #### Props {/*props*/} -`StrictMode` accepts no props. +`StrictMode` não aceita props. -#### Caveats {/*caveats*/} +#### Ressalvas {/*caveats*/} -* There is no way to opt out of Strict Mode inside a tree wrapped in ``. This gives you confidence that all components inside `` are checked. If two teams working on a product disagree whether they find the checks valuable, they need to either reach consensus or move `` down in the tree. +* Não há como optar por sair do Modo Estrito dentro de uma árvore envolvida em ``. Isso dá a você confiança de que todos os componentes dentro de `` estão sendo verificados. Se duas equipes trabalhando em um produto discordarem sobre a validade das verificações, elas precisam chegar a um consenso ou mover `` para baixo na árvore. --- -## Usage {/*usage*/} +## Uso {/*usage*/} -### Enabling Strict Mode for entire app {/*enabling-strict-mode-for-entire-app*/} +### Habilitando o Modo Estrito para todo o aplicativo {/*enabling-strict-mode-for-entire-app*/} -Strict Mode enables extra development-only checks for the entire component tree inside the `` component. These checks help you find common bugs in your components early in the development process. +O Modo Estrito habilita verificações adicionais apenas para desenvolvimento para toda a árvore de componentes dentro do componente ``. Essas verificações ajudam você a encontrar erros comuns em seus componentes no início do processo de desenvolvimento. -To enable Strict Mode for your entire app, wrap your root component with `` when you render it: +Para habilitar o Modo Estrito para todo o seu aplicativo, envolva seu componente raiz com `` ao renderizá-lo: ```js {6,8} import { StrictMode } from 'react'; @@ -77,27 +77,27 @@ root.render( ); ``` -We recommend wrapping your entire app in Strict Mode, especially for newly created apps. If you use a framework that calls [`createRoot`](/reference/react-dom/client/createRoot) for you, check its documentation for how to enable Strict Mode. +Recomendamos envolver todo o seu aplicativo no Modo Estrito, especialmente para aplicativos recém-criados. Se você usar uma biblioteca que chama [`createRoot`](/reference/react-dom/client/createRoot) por você, verifique sua documentação para saber como habilitar o Modo Estrito. -Although the Strict Mode checks **only run in development,** they help you find bugs that already exist in your code but can be tricky to reliably reproduce in production. Strict Mode lets you fix bugs before your users report them. +Embora as verificações do Modo Estrito **executem apenas em desenvolvimento,** elas ajudam você a encontrar erros que já existem em seu código, mas que podem ser difíceis de reproduzir de forma confiável em produção. O Modo Estrito permite que você corrija erros antes que seus usuários os relatem. -Strict Mode enables the following checks in development: +O Modo Estrito habilita as seguintes verificações em desenvolvimento: -- Your components will [re-render an extra time](#fixing-bugs-found-by-double-rendering-in-development) to find bugs caused by impure rendering. -- Your components will [re-run Effects an extra time](#fixing-bugs-found-by-re-running-effects-in-development) to find bugs caused by missing Effect cleanup. -- Your components will [be checked for usage of deprecated APIs.](#fixing-deprecation-warnings-enabled-by-strict-mode) +- Seus componentes serão [re-renderizados uma vez a mais](#fixing-bugs-found-by-double-rendering-in-development) para encontrar erros causados por renderização impura. +- Seus componentes [re-executarão efeitos uma vez a mais](#fixing-bugs-found-by-re-running-effects-in-development) para encontrar erros causados pela ausência de limpeza de efeito. +- Seus componentes [serão verificados quanto ao uso de APIs obsoletas.](#fixing-deprecation-warnings-enabled-by-strict-mode) -**All of these checks are development-only and do not impact the production build.** +**Todas essas verificações são apenas para desenvolvimento e não afetam a construção para produção.** --- -### Enabling Strict Mode for a part of the app {/*enabling-strict-mode-for-a-part-of-the-app*/} +### Habilitando o Modo Estrito para uma parte do aplicativo {/*enabling-strict-mode-for-a-part-of-the-app*/} -You can also enable Strict Mode for any part of your application: +Você também pode habilitar o Modo Estrito para qualquer parte de sua aplicação: ```js {7,12} import { StrictMode } from 'react'; @@ -118,25 +118,25 @@ function App() { } ``` -In this example, Strict Mode checks will not run against the `Header` and `Footer` components. However, they will run on `Sidebar` and `Content`, as well as all of the components inside them, no matter how deep. +Neste exemplo, as verificações do Modo Estrito não serão executadas contra os componentes `Header` e `Footer`. No entanto, elas serão executadas em `Sidebar` e `Content`, bem como todos os componentes dentro deles, não importa quão profundos sejam. --- -### Fixing bugs found by double rendering in development {/*fixing-bugs-found-by-double-rendering-in-development*/} +### Corrigindo erros encontrados por re-renderização em desenvolvimento {/*fixing-bugs-found-by-double-rendering-in-development*/} -[React assumes that every component you write is a pure function.](/learn/keeping-components-pure) This means that React components you write must always return the same JSX given the same inputs (props, state, and context). +[O React assume que cada componente que você escreve é uma função pura.](/learn/keeping-components-pure) Isso significa que os componentes React que você escreve devem sempre retornar o mesmo JSX dadas as mesmas entradas (props, estado e contexto). -Components breaking this rule behave unpredictably and cause bugs. To help you find accidentally impure code, Strict Mode calls some of your functions (only the ones that should be pure) **twice in development.** This includes: +Componentes que quebram essa regra se comportam de forma imprevisível e causam erros. Para ajudar você a encontrar acidentalmente código impuro, o Modo Estrito chama algumas de suas funções (apenas aquelas que deveriam ser puras) **duas vezes em desenvolvimento.** Isso inclui: -- Your component function body (only top-level logic, so this doesn't include code inside event handlers) -- Functions that you pass to [`useState`](/reference/react/useState), [`set` functions](/reference/react/useState#setstate), [`useMemo`](/reference/react/useMemo), or [`useReducer`](/reference/react/useReducer) -- Some class component methods like [`constructor`](/reference/react/Component#constructor), [`render`](/reference/react/Component#render), [`shouldComponentUpdate`](/reference/react/Component#shouldcomponentupdate) ([see the whole list](https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects)) +- O corpo da função do seu componente (apenas a lógica de nível superior, portanto, isso não inclui código dentro de manipuladores de eventos) +- Funções que você passa para [`useState`](/reference/react/useState), [`set` functions](/reference/react/useState#setstate), [`useMemo`](/reference/react/useMemo), ou [`useReducer`](/reference/react/useReducer) +- Alguns métodos de componentes de classe, como [`constructor`](/reference/react/Component#constructor), [`render`](/reference/react/Component#render), [`shouldComponentUpdate`](/reference/react/Component#shouldcomponentupdate) ([veja a lista completa](https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects)) -If a function is pure, running it twice does not change its behavior because a pure function produces the same result every time. However, if a function is impure (for example, it mutates the data it receives), running it twice tends to be noticeable (that's what makes it impure!) This helps you spot and fix the bug early. +Se uma função for pura, executá-la duas vezes não altera seu comportamento porque uma função pura produz o mesmo resultado toda vez. No entanto, se uma função for impura (por exemplo, se ela muta os dados que recebe), executá-la duas vezes tende a ser notável (é isso que a torna impura!) Isso ajuda você a identificar e corrigir o erro mais cedo. -**Here is an example to illustrate how double rendering in Strict Mode helps you find bugs early.** +**Aqui está um exemplo para ilustrar como a re-renderização no Modo Estrito ajuda você a encontrar erros mais cedo.** -This `StoryTray` component takes an array of `stories` and adds one last "Create Story" item at the end: +Este componente `StoryTray` recebe um array de `stories` e adiciona um último item "Criar História" no final: @@ -155,8 +155,8 @@ import { useState } from 'react'; import StoryTray from './StoryTray.js'; let initialStories = [ - {id: 0, label: "Ankit's Story" }, - {id: 1, label: "Taylor's Story" }, + {id: 0, label: "A História de Ankit" }, + {id: 1, label: "A História de Taylor" }, ]; export default function App() { @@ -178,7 +178,7 @@ export default function App() { ```js src/StoryTray.js active export default function StoryTray({ stories }) { const items = stories; - items.push({ id: 'create', label: 'Create Story' }); + items.push({ id: 'create', label: 'Criar História' }); return (
    {items.map(story => ( @@ -214,9 +214,9 @@ li { -There is a mistake in the code above. However, it is easy to miss because the initial output appears correct. +Há um erro no código acima. No entanto, é fácil perder, pois a saída inicial parece correta. -This mistake will become more noticeable if the `StoryTray` component re-renders multiple times. For example, let's make the `StoryTray` re-render with a different background color whenever you hover over it: +Este erro se tornará mais perceptível se o componente `StoryTray` for re-renderizado várias vezes. Por exemplo, vamos fazer com que o `StoryTray` seja re-renderizado com uma cor de fundo diferente sempre que você passar o mouse sobre ele: @@ -235,8 +235,8 @@ import { useState } from 'react'; import StoryTray from './StoryTray.js'; let initialStories = [ - {id: 0, label: "Ankit's Story" }, - {id: 1, label: "Taylor's Story" }, + {id: 0, label: "A História de Ankit" }, + {id: 1, label: "A História de Taylor" }, ]; export default function App() { @@ -261,7 +261,7 @@ import { useState } from 'react'; export default function StoryTray({ stories }) { const [isHover, setIsHover] = useState(false); const items = stories; - items.push({ id: 'create', label: 'Create Story' }); + items.push({ id: 'create', label: 'Criar História' }); return (
      setIsHover(true)} @@ -303,20 +303,20 @@ li { -Notice how every time you hover over the `StoryTray` component, "Create Story" gets added to the list again. The intention of the code was to add it once at the end. But `StoryTray` directly modifies the `stories` array from the props. Every time `StoryTray` renders, it adds "Create Story" again at the end of the same array. In other words, `StoryTray` is not a pure function--running it multiple times produces different results. +Observe como cada vez que você passa o mouse sobre o componente `StoryTray`, "Criar História" é adicionado à lista novamente. A intenção do código era adicioná-lo uma única vez ao final. Mas o `StoryTray` modifica diretamente o array `stories` a partir das props. Cada vez que o `StoryTray` é renderizado, ele adiciona "Criar História" novamente ao final do mesmo array. Em outras palavras, o `StoryTray` não é uma função pura -- executá-lo várias vezes produz resultados diferentes. -To fix this problem, you can make a copy of the array, and modify that copy instead of the original one: +Para corrigir esse problema, você pode fazer uma cópia do array e modificar essa cópia em vez do original: ```js {2} export default function StoryTray({ stories }) { - const items = stories.slice(); // Clone the array - // ✅ Good: Pushing into a new array - items.push({ id: 'create', label: 'Create Story' }); + const items = stories.slice(); // Clona o array + // ✅ Bom: Adicionando a um novo array + items.push({ id: 'create', label: 'Criar História' }); ``` -This would [make the `StoryTray` function pure.](/learn/keeping-components-pure) Each time it is called, it would only modify a new copy of the array, and would not affect any external objects or variables. This solves the bug, but you had to make the component re-render more often before it became obvious that something is wrong with its behavior. +Isso [tornaria a função `StoryTray` pura.](/learn/keeping-components-pure) Cada vez que é chamada, ela apenas modificaria uma nova cópia do array e não afetaria nenhum objeto ou variável externa. Isso resolve o erro, mas você teve que fazer o componente re-renderizar mais vezes antes que ficasse óbvio que algo estava errado com seu comportamento. -**In the original example, the bug wasn't obvious. Now let's wrap the original (buggy) code in ``:** +**No exemplo original, o erro não era óbvio. Agora, vamos envolver o código original (com erro) em ``:** @@ -340,8 +340,8 @@ import { useState } from 'react'; import StoryTray from './StoryTray.js'; let initialStories = [ - {id: 0, label: "Ankit's Story" }, - {id: 1, label: "Taylor's Story" }, + {id: 0, label: "A História de Ankit" }, + {id: 1, label: "A História de Taylor" }, ]; export default function App() { @@ -363,7 +363,7 @@ export default function App() { ```js src/StoryTray.js active export default function StoryTray({ stories }) { const items = stories; - items.push({ id: 'create', label: 'Create Story' }); + items.push({ id: 'create', label: 'Criar História' }); return (
        {items.map(story => ( @@ -399,7 +399,7 @@ li { -**Strict Mode *always* calls your rendering function twice, so you can see the mistake right away** ("Create Story" appears twice). This lets you notice such mistakes early in the process. When you fix your component to render in Strict Mode, you *also* fix many possible future production bugs like the hover functionality from before: +**O Modo Estrito *sempre* chama sua função de renderização duas vezes, então você pode ver o erro imediatamente** ("Criar História" aparece duas vezes). Isso permite que você perceba tais erros cedo no processo. Quando você corrige seu componente para renderizar no Modo Estrito, você *também* corrige muitos possíveis erros futuros de produção, como a funcionalidade de hover mencionada anteriormente: @@ -423,8 +423,8 @@ import { useState } from 'react'; import StoryTray from './StoryTray.js'; let initialStories = [ - {id: 0, label: "Ankit's Story" }, - {id: 1, label: "Taylor's Story" }, + {id: 0, label: "A História de Ankit" }, + {id: 1, label: "A História de Taylor" }, ]; export default function App() { @@ -448,8 +448,8 @@ import { useState } from 'react'; export default function StoryTray({ stories }) { const [isHover, setIsHover] = useState(false); - const items = stories.slice(); // Clone the array - items.push({ id: 'create', label: 'Create Story' }); + const items = stories.slice(); // Clona o array + items.push({ id: 'create', label: 'Criar História' }); return (
          setIsHover(true)} @@ -491,29 +491,29 @@ li { -Without Strict Mode, it was easy to miss the bug until you added more re-renders. Strict Mode made the same bug appear right away. Strict Mode helps you find bugs before you push them to your team and to your users. +Sem o Modo Estrito, era fácil perder o erro até que você adicionasse mais re-renderizações. O Modo Estrito fez o mesmo erro aparecer imediatamente. O Modo Estrito ajuda você a encontrar erros antes de enviá-los para sua equipe e para seus usuários. -[Read more about keeping components pure.](/learn/keeping-components-pure) +[Leia mais sobre como manter os componentes puros.](/learn/keeping-components-pure) -If you have [React DevTools](/learn/react-developer-tools) installed, any `console.log` calls during the second render call will appear slightly dimmed. React DevTools also offers a setting (off by default) to suppress them completely. +Se você tem [React DevTools](/learn/react-developer-tools) instalado, qualquer chamada `console.log` durante a segunda chamada de renderização aparecerá ligeiramente atenuada. O React DevTools também oferece uma configuração (desativada por padrão) para suprimir completamente essas chamadas. --- -### Fixing bugs found by re-running Effects in development {/*fixing-bugs-found-by-re-running-effects-in-development*/} +### Corrigindo erros encontrados ao re-executar Efeitos em desenvolvimento {/*fixing-bugs-found-by-re-running-effects-in-development*/} -Strict Mode can also help find bugs in [Effects.](/learn/synchronizing-with-effects) +O Modo Estrito também pode ajudar a encontrar erros em [Efeitos.](/learn/synchronizing-with-effects) -Every Effect has some setup code and may have some cleanup code. Normally, React calls setup when the component *mounts* (is added to the screen) and calls cleanup when the component *unmounts* (is removed from the screen). React then calls cleanup and setup again if its dependencies changed since the last render. +Todo Efeito tem algum código de configuração e pode ter algum código de limpeza. Normalmente, o React chama a configuração quando o componente *monta* (é adicionado à tela) e chama a limpeza quando o componente *desmonta* (é removido da tela). O React então chama a limpeza e a configuração novamente se suas dependências mudaram desde a última renderização. -When Strict Mode is on, React will also run **one extra setup+cleanup cycle in development for every Effect.** This may feel surprising, but it helps reveal subtle bugs that are hard to catch manually. +Quando o Modo Estrito está ativo, o React também executará **um ciclo extra de configuração+limpeza no desenvolvimento para cada Efeito.** Isso pode parecer surpreendente, mas ajuda a revelar erros sutis que são difíceis de pegar manualmente. -**Here is an example to illustrate how re-running Effects in Strict Mode helps you find bugs early.** +**Aqui está um exemplo para ilustrar como a re-execução de Efeitos no Modo Estrito ajuda você a encontrar erros mais cedo.** -Consider this example that connects a component to a chat: +Considere este exemplo que conecta um componente a um chat: @@ -532,14 +532,14 @@ import { useState, useEffect } from 'react'; import { createConnection } from './chat.js'; const serverUrl = 'https://localhost:1234'; -const roomId = 'general'; +const roomId = 'geral'; export default function ChatRoom() { useEffect(() => { const connection = createConnection(serverUrl, roomId); connection.connect(); }, []); - return

          Welcome to the {roomId} room!

          ; + return

          Bem-vindo à sala {roomId}!

          ; } ``` @@ -547,17 +547,17 @@ export default function ChatRoom() { let connections = 0; export function createConnection(serverUrl, roomId) { - // A real implementation would actually connect to the server + // Uma implementação real realmente se conectaria ao servidor return { connect() { - console.log('✅ Connecting to "' + roomId + '" room at ' + serverUrl + '...'); + console.log('✅ Conectando à sala "' + roomId + '" em ' + serverUrl + '...'); connections++; - console.log('Active connections: ' + connections); + console.log('Conexões ativas: ' + connections); }, disconnect() { - console.log('❌ Disconnected from "' + roomId + '" room at ' + serverUrl); + console.log('❌ Desconectado da sala "' + roomId + '" em ' + serverUrl); connections--; - console.log('Active connections: ' + connections); + console.log('Conexões ativas: ' + connections); } }; } @@ -570,9 +570,9 @@ button { margin-left: 10px; }
          -There is an issue with this code, but it might not be immediately clear. +Há um problema com este código, mas pode não ser imediatamente claro. -To make the issue more obvious, let's implement a feature. In the example below, `roomId` is not hardcoded. Instead, the user can select the `roomId` that they want to connect to from a dropdown. Click "Open chat" and then select different chat rooms one by one. Keep track of the number of active connections in the console: +Para tornar o problema mais óbvio, vamos implementar um recurso. No exemplo abaixo, `roomId` não está codificado. Em vez disso, o usuário pode selecionar o `roomId` que deseja conectar a partir de um dropdown. Clique em "Abrir chat" e então selecione diferentes salas de chat uma a uma. Mantenha controle do número de conexões ativas no console: @@ -598,27 +598,27 @@ function ChatRoom({ roomId }) { connection.connect(); }, [roomId]); - return

          Welcome to the {roomId} room!

          ; + return

          Bem-vindo à sala {roomId}!

          ; } export default function App() { - const [roomId, setRoomId] = useState('general'); + const [roomId, setRoomId] = useState('geral'); const [show, setShow] = useState(false); return ( <> {show &&
          } {show && } @@ -631,17 +631,17 @@ export default function App() { let connections = 0; export function createConnection(serverUrl, roomId) { - // A real implementation would actually connect to the server + // Uma implementação real realmente se conectaria ao servidor return { connect() { - console.log('✅ Connecting to "' + roomId + '" room at ' + serverUrl + '...'); + console.log('✅ Conectando à sala "' + roomId + '" em ' + serverUrl + '...'); connections++; - console.log('Active connections: ' + connections); + console.log('Conexões ativas: ' + connections); }, disconnect() { - console.log('❌ Disconnected from "' + roomId + '" room at ' + serverUrl); + console.log('❌ Desconectado da sala "' + roomId + '" em ' + serverUrl); connections--; - console.log('Active connections: ' + connections); + console.log('Conexões ativas: ' + connections); } }; } @@ -654,7 +654,7 @@ button { margin-left: 10px; }
          -You'll notice that the number of open connections always keeps growing. In a real app, this would cause performance and network problems. The issue is that [your Effect is missing a cleanup function:](/learn/synchronizing-with-effects#step-3-add-cleanup-if-needed) +Você notará que o número de conexões abertas sempre continua aumentando. Em um aplicativo real, isso causaria problemas de desempenho e rede. O problema é que [seu Efeito está faltando uma função de limpeza:](/learn/synchronizing-with-effects#step-3-add-cleanup-if-needed) ```js {4} useEffect(() => { @@ -664,9 +664,9 @@ You'll notice that the number of open connections always keeps growing. In a rea }, [roomId]); ``` -Now that your Effect "cleans up" after itself and destroys the outdated connections, the leak is solved. However, notice that the problem did not become visible until you've added more features (the select box). +Agora que seu Efeito "limpa" após si mesmo e destrói as conexões desatualizadas, o vazamento está resolvido. No entanto, note que o problema não se tornou visível até que você adicionasse mais recursos (a caixa de seleção). -**In the original example, the bug wasn't obvious. Now let's wrap the original (buggy) code in ``:** +**No exemplo original, o erro não era óbvio. Agora vamos envolver o código original (bugado) em ``:** @@ -690,14 +690,14 @@ import { useState, useEffect } from 'react'; import { createConnection } from './chat.js'; const serverUrl = 'https://localhost:1234'; -const roomId = 'general'; +const roomId = 'geral'; export default function ChatRoom() { useEffect(() => { const connection = createConnection(serverUrl, roomId); connection.connect(); }, []); - return

          Welcome to the {roomId} room!

          ; + return

          Bem-vindo à sala {roomId}!

          ; } ``` @@ -705,17 +705,17 @@ export default function ChatRoom() { let connections = 0; export function createConnection(serverUrl, roomId) { - // A real implementation would actually connect to the server + // Uma implementação real realmente se conectaria ao servidor return { connect() { - console.log('✅ Connecting to "' + roomId + '" room at ' + serverUrl + '...'); + console.log('✅ Conectando à sala "' + roomId + '" em ' + serverUrl + '...'); connections++; - console.log('Active connections: ' + connections); + console.log('Conexões ativas: ' + connections); }, disconnect() { - console.log('❌ Disconnected from "' + roomId + '" room at ' + serverUrl); + console.log('❌ Desconectado da sala "' + roomId + '" em ' + serverUrl); connections--; - console.log('Active connections: ' + connections); + console.log('Conexões ativas: ' + connections); } }; } @@ -728,9 +728,9 @@ button { margin-left: 10px; }
          -**With Strict Mode, you immediately see that there is a problem** (the number of active connections jumps to 2). Strict Mode runs an extra setup+cleanup cycle for every Effect. This Effect has no cleanup logic, so it creates an extra connection but doesn't destroy it. This is a hint that you're missing a cleanup function. +**Com o Modo Estrito, você imediatamente vê que há um problema** (o número de conexões ativas salta para 2). O Modo Estrito executa um ciclo extra de configuração+limpeza para cada Efeito. Esse Efeito não tem lógica de limpeza, então cria uma conexão extra, mas não a destrói. Isso serve como um sinal de que você está perdendo uma função de limpeza. -Strict Mode lets you notice such mistakes early in the process. When you fix your Effect by adding a cleanup function in Strict Mode, you *also* fix many possible future production bugs like the select box from before: +O Modo Estrito permite que você perceba tais erros cedo no processo. Quando você corrige seu Efeito adicionando uma função de limpeza no Modo Estrito, você *também* corrige muitos possíveis erros futuros de produção, como a caixa de seleção mencionada anteriormente: @@ -762,27 +762,27 @@ function ChatRoom({ roomId }) { return () => connection.disconnect(); }, [roomId]); - return

          Welcome to the {roomId} room!

          ; + return

          Bem-vindo à sala {roomId}!

          ; } export default function App() { - const [roomId, setRoomId] = useState('general'); + const [roomId, setRoomId] = useState('geral'); const [show, setShow] = useState(false); return ( <> {show &&
          } {show && } @@ -795,17 +795,17 @@ export default function App() { let connections = 0; export function createConnection(serverUrl, roomId) { - // A real implementation would actually connect to the server + // Uma implementação real realmente se conectaria ao servidor return { connect() { - console.log('✅ Connecting to "' + roomId + '" room at ' + serverUrl + '...'); + console.log('✅ Conectando à sala "' + roomId + '" em ' + serverUrl + '...'); connections++; - console.log('Active connections: ' + connections); + console.log('Conexões ativas: ' + connections); }, disconnect() { - console.log('❌ Disconnected from "' + roomId + '" room at ' + serverUrl); + console.log('❌ Desconectado da sala "' + roomId + '" em ' + serverUrl); connections--; - console.log('Active connections: ' + connections); + console.log('Conexões ativas: ' + connections); } }; } @@ -818,21 +818,21 @@ button { margin-left: 10px; }
          -Notice how the active connection count in the console doesn't keep growing anymore. +Observe como a contagem de conexões ativas no console não continua crescendo. -Without Strict Mode, it was easy to miss that your Effect needed cleanup. By running *setup → cleanup → setup* instead of *setup* for your Effect in development, Strict Mode made the missing cleanup logic more noticeable. +Sem o Modo Estrito, era fácil perder que seu Efeito precisava de limpeza. Ao executar *configuração → limpeza → configuração* em vez de apenas *configuração* para seu Efeito no desenvolvimento, o Modo Estrito tornou a lógica de limpeza ausente mais perceptível. -[Read more about implementing Effect cleanup.](/learn/synchronizing-with-effects#how-to-handle-the-effect-firing-twice-in-development) +[Leia mais sobre como implementar a limpeza de Efeitos.](/learn/synchronizing-with-effects#how-to-handle-the-effect-firing-twice-in-development) --- -### Fixing deprecation warnings enabled by Strict Mode {/*fixing-deprecation-warnings-enabled-by-strict-mode*/} +### Corrigindo avisos de depreciação habilitados pelo Modo Estrito {/*fixing-deprecation-warnings-enabled-by-strict-mode*/} -React warns if some component anywhere inside a `` tree uses one of these deprecated APIs: +O React avisa se algum componente em algum lugar dentro de uma árvore `` usa uma dessas APIs obsoletas: -* [`findDOMNode`](/reference/react-dom/findDOMNode). [See alternatives.](https://reactjs.org/docs/strict-mode.html#warning-about-deprecated-finddomnode-usage) -* `UNSAFE_` class lifecycle methods like [`UNSAFE_componentWillMount`](/reference/react/Component#unsafe_componentwillmount). [See alternatives.](https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#migrating-from-legacy-lifecycles) -* Legacy context ([`childContextTypes`](/reference/react/Component#static-childcontexttypes), [`contextTypes`](/reference/react/Component#static-contexttypes), and [`getChildContext`](/reference/react/Component#getchildcontext)). [See alternatives.](/reference/react/createContext) -* Legacy string refs ([`this.refs`](/reference/react/Component#refs)). [See alternatives.](https://reactjs.org/docs/strict-mode.html#warning-about-legacy-string-ref-api-usage) +* [`findDOMNode`](/reference/react-dom/findDOMNode). [Veja alternativas.](https://reactjs.org/docs/strict-mode.html#warning-about-deprecated-finddomnode-usage) +* Métodos de ciclo de vida de classe `UNSAFE_`, como [`UNSAFE_componentWillMount`](/reference/react/Component#unsafe_componentwillmount). [Veja alternativas.](https://reactjs.org/blog/2018/03/27/update-on-async-rendering.html#migrating-from-legacy-lifecycles) +* Contexto legado ([`childContextTypes`](/reference/react/Component#static-childcontexttypes), [`contextTypes`](/reference/react/Component#static-contexttypes), e [`getChildContext`](/reference/react/Component#getchildcontext)). [Veja alternativas.](/reference/react/createContext) +* Referências de string legado ([`this.refs`](/reference/react/Component#refs)). [Veja alternativas.](https://reactjs.org/docs/strict-mode.html#warning-about-legacy-string-ref-api-usage) -These APIs are primarily used in older [class components](/reference/react/Component) so they rarely appear in modern apps. +Essas APIs são principalmente usadas em componentes de classe mais antigos, portanto, raramente aparecem em aplicativos modernos. \ No newline at end of file