diff --git a/src/content/learn/lifecycle-of-reactive-effects.md b/src/content/learn/lifecycle-of-reactive-effects.md index 3dc9a75f0..833f63c72 100644 --- a/src/content/learn/lifecycle-of-reactive-effects.md +++ b/src/content/learn/lifecycle-of-reactive-effects.md @@ -1,37 +1,37 @@ --- -title: 'Lifecycle of Reactive Effects' +title: 'Ciclo de Vida dos Efeitos Reativos' --- -Effects have a different lifecycle from components. Components may mount, update, or unmount. An Effect can only do two things: to start synchronizing something, and later to stop synchronizing it. This cycle can happen multiple times if your Effect depends on props and state that change over time. React provides a linter rule to check that you've specified your Effect's dependencies correctly. This keeps your Effect synchronized to the latest props and state. +Os Efeitos têm um ciclo de vida diferente dos componentes. Componentes podem montar, atualizar ou desmontar. Um Efeito pode fazer apenas duas coisas: começar a sincronizar algo e, mais tarde, parar de sincronizá-lo. Este ciclo pode acontecer várias vezes se o seu Efeito depender de props e estados que mudam ao longo do tempo. O React fornece uma regra de lint para verificar se você especificou corretamente as dependências do seu Efeito. Isso mantém seu Efeito sincronizado com as últimas props e estado. -- How an Effect's lifecycle is different from a component's lifecycle -- How to think about each individual Effect in isolation -- When your Effect needs to re-synchronize, and why -- How your Effect's dependencies are determined -- What it means for a value to be reactive -- What an empty dependency array means -- How React verifies your dependencies are correct with a linter -- What to do when you disagree with the linter +- Como o ciclo de vida de um Efeito é diferente do ciclo de vida de um componente +- Como pensar sobre cada Efeito individualmente em isolamento +- Quando seu Efeito precisa re-sincronizar e por quê +- Como as dependências do seu Efeito são determinadas +- O que significa um valor ser reativo +- O que significa um array de dependências vazio +- Como o React verifica se suas dependências estão corretas com um linter +- O que fazer quando você discorda do linter -## The lifecycle of an Effect {/*the-lifecycle-of-an-effect*/} +## O ciclo de vida de um Efeito {/*the-lifecycle-of-an-effect*/} -Every React component goes through the same lifecycle: +Todo componente React passa pelo mesmo ciclo de vida: -- A component _mounts_ when it's added to the screen. -- A component _updates_ when it receives new props or state, usually in response to an interaction. -- A component _unmounts_ when it's removed from the screen. +- Um componente _monta_ quando é adicionado à tela. +- Um componente _atualiza_ quando recebe novas props ou estado, geralmente em resposta a uma interação. +- Um componente _desmonta_ quando é removido da tela. -**It's a good way to think about components, but _not_ about Effects.** Instead, try to think about each Effect independently from your component's lifecycle. An Effect describes how to [synchronize an external system](/learn/synchronizing-with-effects) to the current props and state. As your code changes, synchronization will need to happen more or less often. +**É uma boa maneira de pensar sobre componentes, mas _não_ sobre Efeitos.** Em vez disso, tente pensar em cada Efeito de forma independente do ciclo de vida do seu componente. Um Efeito descreve como [sincronizar um sistema externo](/learn/synchronizing-with-effects) com as props e estado atuais. À medida que seu código muda, a sincronização precisará acontecer mais ou menos frequentemente. -To illustrate this point, consider this Effect connecting your component to a chat server: +Para ilustrar este ponto, considere este Efeito conectando seu componente a um servidor de chat: ```js const serverUrl = 'https://localhost:1234'; @@ -48,7 +48,7 @@ function ChatRoom({ roomId }) { } ``` -Your Effect's body specifies how to **start synchronizing:** +O corpo do seu Efeito especifica como **começar a sincronizar:** ```js {2-3} // ... @@ -60,7 +60,7 @@ Your Effect's body specifies how to **start synchronizing:** // ... ``` -The cleanup function returned by your Effect specifies how to **stop synchronizing:** +A função de limpeza retornada pelo seu Efeito especifica como **parar de sincronizar:** ```js {5} // ... @@ -72,141 +72,141 @@ The cleanup function returned by your Effect specifies how to **stop synchronizi // ... ``` -Intuitively, you might think that React would **start synchronizing** when your component mounts and **stop synchronizing** when your component unmounts. However, this is not the end of the story! Sometimes, it may also be necessary to **start and stop synchronizing multiple times** while the component remains mounted. +Intuitivamente, você pode pensar que o React **começaria a sincronizar** quando seu componente monta e **pararia de sincronizar** quando seu componente desmonta. No entanto, este não é o fim da história! Às vezes, pode ser necessário **começar e parar de sincronizar várias vezes** enquanto o componente permanece montado. -Let's look at _why_ this is necessary, _when_ it happens, and _how_ you can control this behavior. +Vamos analisar _por que_ isso é necessário, _quando_ isso acontece e _como_ você pode controlar esse comportamento. -Some Effects don't return a cleanup function at all. [More often than not,](/learn/synchronizing-with-effects#how-to-handle-the-effect-firing-twice-in-development) you'll want to return one--but if you don't, React will behave as if you returned an empty cleanup function. +Alguns Efeitos não retornam uma função de limpeza. [Mais frequentemente do que não,](/learn/synchronizing-with-effects#how-to-handle-the-effect-firing-twice-in-development) você vai querer retornar uma--mas se não o fizer, o React se comportará como se você tivesse retornado uma função de limpeza vazia. -### Why synchronization may need to happen more than once {/*why-synchronization-may-need-to-happen-more-than-once*/} +### Por que a sincronização pode precisar acontecer mais de uma vez {/*why-synchronization-may-need-to-happen-more-than-once*/} -Imagine this `ChatRoom` component receives a `roomId` prop that the user picks in a dropdown. Let's say that initially the user picks the `"general"` room as the `roomId`. Your app displays the `"general"` chat room: +Imagine que este componente `ChatRoom` recebe uma prop `roomId` que o usuário escolhe em um dropdown. Vamos supor que inicialmente o usuário escolha a sala `"general"` como o `roomId`. Seu aplicativo exibe a sala de chat `"general"`: ```js {3} const serverUrl = 'https://localhost:1234'; function ChatRoom({ roomId /* "general" */ }) { // ... - return

Welcome to the {roomId} room!

; + return

Bem-vindo à sala {roomId}!

; } ``` -After the UI is displayed, React will run your Effect to **start synchronizing.** It connects to the `"general"` room: +Depois que a UI é exibida, o React executará seu Efeito para **começar a sincronizar.** Ele se conecta à sala `"general"`: ```js {3,4} function ChatRoom({ roomId /* "general" */ }) { useEffect(() => { - const connection = createConnection(serverUrl, roomId); // Connects to the "general" room + const connection = createConnection(serverUrl, roomId); // Conecta-se à sala "general" connection.connect(); return () => { - connection.disconnect(); // Disconnects from the "general" room + connection.disconnect(); // Desconecta da sala "general" }; }, [roomId]); // ... ``` -So far, so good. +Até aqui, tudo certo. -Later, the user picks a different room in the dropdown (for example, `"travel"`). First, React will update the UI: +Mais tarde, o usuário escolhe uma sala diferente no dropdown (por exemplo, `"travel"`). Primeiro, o React atualizará a UI: ```js {1} function ChatRoom({ roomId /* "travel" */ }) { // ... - return

Welcome to the {roomId} room!

; + return

Bem-vindo à sala {roomId}!

; } ``` -Think about what should happen next. The user sees that `"travel"` is the selected chat room in the UI. However, the Effect that ran the last time is still connected to the `"general"` room. **The `roomId` prop has changed, so what your Effect did back then (connecting to the `"general"` room) no longer matches the UI.** +Pense sobre o que deve acontecer a seguir. O usuário vê que `"travel"` é a sala de chat selecionada na UI. No entanto, o Efeito que foi executado da última vez ainda está conectado à sala `"general"`. **A prop `roomId` mudou, então o que seu Efeito fez na última vez (conectando-se à sala `"general"`) não corresponde mais à UI.** -At this point, you want React to do two things: +Neste ponto, você gostaria que o React fizesse duas coisas: -1. Stop synchronizing with the old `roomId` (disconnect from the `"general"` room) -2. Start synchronizing with the new `roomId` (connect to the `"travel"` room) +1. Parar de sincronizar com o antigo `roomId` (desconectar da sala `"general"`) +2. Começar a sincronizar com o novo `roomId` (conectar à sala `"travel"`) -**Luckily, you've already taught React how to do both of these things!** Your Effect's body specifies how to start synchronizing, and your cleanup function specifies how to stop synchronizing. All that React needs to do now is to call them in the correct order and with the correct props and state. Let's see how exactly that happens. +**Felizmente, você já ensinou ao React como fazer ambas essas coisas!** O corpo do seu Efeito especifica como começar a sincronizar, e sua função de limpeza especifica como parar de sincronizar. Tudo o que o React precisa fazer agora é chamá-los na ordem correta e com as props e estado corretos. Vamos ver como exatamente isso acontece. -### How React re-synchronizes your Effect {/*how-react-re-synchronizes-your-effect*/} +### Como o React re-sincroniza seu Efeito {/*how-react-re-synchronizes-your-effect*/} -Recall that your `ChatRoom` component has received a new value for its `roomId` prop. It used to be `"general"`, and now it is `"travel"`. React needs to re-synchronize your Effect to re-connect you to a different room. +Lembre-se de que seu componente `ChatRoom` recebeu um novo valor para sua prop `roomId`. Antes, era `"general"` e agora é `"travel"`. O React precisa re-sincronizar seu Efeito para reconectá-lo a uma sala diferente. -To **stop synchronizing,** React will call the cleanup function that your Effect returned after connecting to the `"general"` room. Since `roomId` was `"general"`, the cleanup function disconnects from the `"general"` room: +Para **parar de sincronizar,** o React chamará a função de limpeza que seu Efeito retornou após se conectar à sala `"general"`. Como `roomId` era `"general"`, a função de limpeza desconecta da sala `"general"`: ```js {6} function ChatRoom({ roomId /* "general" */ }) { useEffect(() => { - const connection = createConnection(serverUrl, roomId); // Connects to the "general" room + const connection = createConnection(serverUrl, roomId); // Conecta-se à sala "general" connection.connect(); return () => { - connection.disconnect(); // Disconnects from the "general" room + connection.disconnect(); // Desconecta da sala "general" }; // ... ``` -Then React will run the Effect that you've provided during this render. This time, `roomId` is `"travel"` so it will **start synchronizing** to the `"travel"` chat room (until its cleanup function is eventually called too): +Depois, o React executará o Efeito que você forneceu durante esta renderização. Desta vez, `roomId` é `"travel"` então ele **começará a sincronizar** com a sala de chat `"travel"` (até que sua função de limpeza seja eventualmente chamada também): ```js {3,4} function ChatRoom({ roomId /* "travel" */ }) { useEffect(() => { - const connection = createConnection(serverUrl, roomId); // Connects to the "travel" room + const connection = createConnection(serverUrl, roomId); // Conecta-se à sala "travel" connection.connect(); // ... ``` -Thanks to this, you're now connected to the same room that the user chose in the UI. Disaster averted! +Graças a isso, agora você está conectado à mesma sala que o usuário escolheu na UI. Desastre evitado! -Every time after your component re-renders with a different `roomId`, your Effect will re-synchronize. For example, let's say the user changes `roomId` from `"travel"` to `"music"`. React will again **stop synchronizing** your Effect by calling its cleanup function (disconnecting you from the `"travel"` room). Then it will **start synchronizing** again by running its body with the new `roomId` prop (connecting you to the `"music"` room). +Toda vez que seu componente re-renderiza com um `roomId` diferente, seu Efeito será re-sincronizado. Por exemplo, vamos supor que o usuário muda `roomId` de `"travel"` para `"music"`. O React novamente **parará de sincronizar** seu Efeito chamando sua função de limpeza (desconectando-o da sala `"travel"`). Então, ele **começará a sincronizar** novamente executando seu corpo com a nova prop `roomId` (conectando-o à sala `"music"`). -Finally, when the user goes to a different screen, `ChatRoom` unmounts. Now there is no need to stay connected at all. React will **stop synchronizing** your Effect one last time and disconnect you from the `"music"` chat room. +Finalmente, quando o usuário vai para uma tela diferente, `ChatRoom` desmonta. Agora não há necessidade de permanecer conectado. O React **parará de sincronizar** seu Efeito uma última vez e desconectará você da sala de chat `"music"`. -### Thinking from the Effect's perspective {/*thinking-from-the-effects-perspective*/} +### Pensando da perspectiva do Efeito {/*thinking-from-the-effects-perspective*/} -Let's recap everything that's happened from the `ChatRoom` component's perspective: +Vamos recapitular tudo o que aconteceu da perspectiva do componente `ChatRoom`: -1. `ChatRoom` mounted with `roomId` set to `"general"` -1. `ChatRoom` updated with `roomId` set to `"travel"` -1. `ChatRoom` updated with `roomId` set to `"music"` -1. `ChatRoom` unmounted +1. `ChatRoom` montou com `roomId` definido como `"general"` +1. `ChatRoom` atualizou com `roomId` definido como `"travel"` +1. `ChatRoom` atualizou com `roomId` definido como `"music"` +1. `ChatRoom` desmontou -During each of these points in the component's lifecycle, your Effect did different things: +Durante cada um desses pontos no ciclo de vida do componente, seu Efeito fez coisas diferentes: -1. Your Effect connected to the `"general"` room -1. Your Effect disconnected from the `"general"` room and connected to the `"travel"` room -1. Your Effect disconnected from the `"travel"` room and connected to the `"music"` room -1. Your Effect disconnected from the `"music"` room +1. Seu Efeito conectou-se à sala `"general"` +1. Seu Efeito desconectou da sala `"general"` e conectou na sala `"travel"` +1. Seu Efeito desconectou da sala `"travel"` e conectou na sala `"music"` +1. Seu Efeito desconectou da sala `"music"` -Now let's think about what happened from the perspective of the Effect itself: +Agora vamos pensar sobre o que aconteceu da perspectiva do próprio Efeito: ```js useEffect(() => { - // Your Effect connected to the room specified with roomId... + // Seu Efeito conectou-se à sala especificada com roomId... const connection = createConnection(serverUrl, roomId); connection.connect(); return () => { - // ...until it disconnected + // ...até que se desconectou connection.disconnect(); }; }, [roomId]); ``` -This code's structure might inspire you to see what happened as a sequence of non-overlapping time periods: +A estrutura desse código pode inspirá-lo a ver o que aconteceu como uma sequência de períodos de tempo não sobrepostos: -1. Your Effect connected to the `"general"` room (until it disconnected) -1. Your Effect connected to the `"travel"` room (until it disconnected) -1. Your Effect connected to the `"music"` room (until it disconnected) +1. Seu Efeito conectou-se à sala `"general"` (até se desconectar) +1. Seu Efeito conectou-se à sala `"travel"` (até se desconectar) +1. Seu Efeito conectou-se à sala `"music"` (até se desconectar) -Previously, you were thinking from the component's perspective. When you looked from the component's perspective, it was tempting to think of Effects as "callbacks" or "lifecycle events" that fire at a specific time like "after a render" or "before unmount". This way of thinking gets complicated very fast, so it's best to avoid. +Anteriormente, você estava pensando da perspectiva do componente. Quando você olhou da perspectiva do componente, era tentador pensar nos Efeitos como "callbacks" ou "eventos de ciclo de vida" que disparam em um momento específico, como "após uma renderização" ou "antes de desmontar". Essa forma de pensar fica complicada muito rapidamente, então é melhor evitar. -**Instead, always focus on a single start/stop cycle at a time. It shouldn't matter whether a component is mounting, updating, or unmounting. All you need to do is to describe how to start synchronization and how to stop it. If you do it well, your Effect will be resilient to being started and stopped as many times as it's needed.** +**Em vez disso, concentre-se sempre em um único ciclo de início/parada de cada vez. Não deve importar se um componente está montando, atualizando ou desmontando. Tudo o que você precisa fazer é descrever como iniciar a sincronização e como parar. Se você fizer isso bem, seu Efeito resistirá a ser iniciado e interrompido quantas vezes forem necessárias.** -This might remind you how you don't think whether a component is mounting or updating when you write the rendering logic that creates JSX. You describe what should be on the screen, and React [figures out the rest.](/learn/reacting-to-input-with-state) +Isso pode lembrá-lo de como você não pensa se um componente está montando ou atualizando quando escreve a lógica de renderização que cria JSX. Você descreve o que deve estar na tela, e o React [decide o resto.](/learn/reacting-to-input-with-state) -### How React verifies that your Effect can re-synchronize {/*how-react-verifies-that-your-effect-can-re-synchronize*/} +### Como o React verifica que seu Efeito pode re-sincronizar {/*how-react-verifies-that-your-effect-can-re-synchronize*/} -Here is a live example that you can play with. Press "Open chat" to mount the `ChatRoom` component: +Aqui está um exemplo ao vivo com o qual você pode brincar. Pressione "Abrir chat" para montar o componente `ChatRoom`: @@ -222,7 +222,7 @@ function ChatRoom({ roomId }) { connection.connect(); return () => connection.disconnect(); }, [roomId]); - return

Welcome to the {roomId} room!

; + return

Bem-vindo à sala {roomId}!

; } export default function App() { @@ -231,7 +231,7 @@ export default function App() { return ( <> {show &&
} {show && } @@ -253,13 +253,13 @@ export default function App() { ```js src/chat.js export function createConnection(serverUrl, roomId) { - // A real implementation would actually connect to the server + // Uma implementação real conectaria realmente ao servidor return { connect() { - console.log('✅ Connecting to "' + roomId + '" room at ' + serverUrl + '...'); + console.log('✅ Conectando à sala "' + roomId + '" em ' + serverUrl + '...'); }, disconnect() { - console.log('❌ Disconnected from "' + roomId + '" room at ' + serverUrl); + console.log('❌ Desconectado da sala "' + roomId + '" em ' + serverUrl); } }; } @@ -272,49 +272,49 @@ button { margin-left: 10px; }
-Notice that when the component mounts for the first time, you see three logs: +Perceba que quando o componente monta pela primeira vez, você vê três logs: -1. `✅ Connecting to "general" room at https://localhost:1234...` *(development-only)* -1. `❌ Disconnected from "general" room at https://localhost:1234.` *(development-only)* -1. `✅ Connecting to "general" room at https://localhost:1234...` +1. `✅ Conectando à sala "general" em https://localhost:1234...` *(somente no desenvolvimento)* +1. `❌ Desconectado da sala "general" em https://localhost:1234.` *(somente no desenvolvimento)* +1. `✅ Conectando à sala "general" em https://localhost:1234...` -The first two logs are development-only. In development, React always remounts each component once. +Os dois primeiros logs são somente para desenvolvimento. No desenvolvimento, o React sempre desmonta cada componente uma vez. -**React verifies that your Effect can re-synchronize by forcing it to do that immediately in development.** This might remind you of opening a door and closing it an extra time to check if the door lock works. React starts and stops your Effect one extra time in development to check [you've implemented its cleanup well.](/learn/synchronizing-with-effects#how-to-handle-the-effect-firing-twice-in-development) +**O React verifica que seu Efeito pode re-sincronizar forçando-o a fazer isso imediatamente em desenvolvimento.** Isso pode lembrá-lo de abrir uma porta e fechá-la uma vez a mais para verificar se a fechadura da porta funciona. O React inicia e para seu Efeito uma vez a mais no desenvolvimento para verificar [se você implementou a limpeza bem.](/learn/synchronizing-with-effects#how-to-handle-the-effect-firing-twice-in-development) -The main reason your Effect will re-synchronize in practice is if some data it uses has changed. In the sandbox above, change the selected chat room. Notice how, when the `roomId` changes, your Effect re-synchronizes. +A principal razão pela qual seu Efeito re-sincronizará na prática é se alguns dos dados que ele usa mudaram. No sandbox acima, altere a sala de chat selecionada. Perceba que, quando o `roomId` muda, seu Efeito re-sincroniza. -However, there are also more unusual cases in which re-synchronization is necessary. For example, try editing the `serverUrl` in the sandbox above while the chat is open. Notice how the Effect re-synchronizes in response to your edits to the code. In the future, React may add more features that rely on re-synchronization. +No entanto, há também casos mais incomuns em que a re-sincronização é necessária. Por exemplo, tente editar o `serverUrl` no sandbox acima enquanto o chat está aberto. Perceba como o Efeito re-sincroniza em resposta às suas edições ao código. No futuro, o React pode adicionar mais recursos que dependem da re-sincronização. -### How React knows that it needs to re-synchronize the Effect {/*how-react-knows-that-it-needs-to-re-synchronize-the-effect*/} +### Como o React sabe que precisa re-sincronizar o Efeito {/*how-react-knows-that-it-needs-to-re-synchronize-the-effect*/} -You might be wondering how React knew that your Effect needed to re-synchronize after `roomId` changes. It's because *you told React* that its code depends on `roomId` by including it in the [list of dependencies:](/learn/synchronizing-with-effects#step-2-specify-the-effect-dependencies) +Você pode estar se perguntando como o React sabia que seu Efeito precisava re-sincronizar após as mudanças no `roomId`. É porque *você disse ao React* que seu código depende de `roomId` ao incluí-lo na [lista de dependências:](/learn/synchronizing-with-effects#step-2-specify-the-effect-dependencies) ```js {1,3,8} -function ChatRoom({ roomId }) { // The roomId prop may change over time +function ChatRoom({ roomId }) { // A prop roomId pode mudar ao longo do tempo useEffect(() => { - const connection = createConnection(serverUrl, roomId); // This Effect reads roomId + const connection = createConnection(serverUrl, roomId); // Este Efeito lê roomId connection.connect(); return () => { connection.disconnect(); }; - }, [roomId]); // So you tell React that this Effect "depends on" roomId + }, [roomId]); // Então você diz ao React que este Efeito "depende de" roomId // ... ``` -Here's how this works: +Aqui está como isso funciona: -1. You knew `roomId` is a prop, which means it can change over time. -2. You knew that your Effect reads `roomId` (so its logic depends on a value that may change later). -3. This is why you specified it as your Effect's dependency (so that it re-synchronizes when `roomId` changes). +1. Você sabia que `roomId` é uma prop, o que significa que pode mudar ao longo do tempo. +2. Você sabia que seu Efeito lê `roomId` (então sua lógica depende de um valor que pode mudar mais tarde). +3. É por isso que você especificou isso como uma dependência do seu Efeito (para que ele re-sincronize quando `roomId` muda). -Every time after your component re-renders, React will look at the array of dependencies that you have passed. If any of the values in the array is different from the value at the same spot that you passed during the previous render, React will re-synchronize your Effect. +Toda vez que seu componente re-renderiza, o React olhará para o array de dependências que você passou. Se algum dos valores no array for diferente do valor no mesmo lugar que você passou durante a renderização anterior, o React re-sincronizará seu Efeito. -For example, if you passed `["general"]` during the initial render, and later you passed `["travel"]` during the next render, React will compare `"general"` and `"travel"`. These are different values (compared with [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is)), so React will re-synchronize your Effect. On the other hand, if your component re-renders but `roomId` has not changed, your Effect will remain connected to the same room. +Por exemplo, se você passou `["general"]` durante a renderização inicial e depois passou `["travel"]` durante a próxima renderização, o React comparará `"general"` e `"travel"`. Esses são valores diferentes (comparados com [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is)), então o React re-sincronizará seu Efeito. Por outro lado, se seu componente re-renderiza, mas `roomId` não mudou, seu Efeito permanecerá conectado à mesma sala. -### Each Effect represents a separate synchronization process {/*each-effect-represents-a-separate-synchronization-process*/} +### Cada Efeito representa um processo de sincronização separado {/*each-effect-represents-a-separate-synchronization-process*/} -Resist adding unrelated logic to your Effect only because this logic needs to run at the same time as an Effect you already wrote. For example, let's say you want to send an analytics event when the user visits the room. You already have an Effect that depends on `roomId`, so you might feel tempted to add the analytics call there: +Resista à tentação de adicionar lógica não relacionada ao seu Efeito apenas porque essa lógica precisa ser executada ao mesmo tempo que um Efeito que você já escreveu. Por exemplo, digamos que você queira registrar um evento de análise quando o usuário visita a sala. Você já tem um Efeito que depende de `roomId`, então pode sentir a tentação de adicionar a chamada de análise lá: ```js {3} function ChatRoom({ roomId }) { @@ -330,7 +330,7 @@ function ChatRoom({ roomId }) { } ``` -But imagine you later add another dependency to this Effect that needs to re-establish the connection. If this Effect re-synchronizes, it will also call `logVisit(roomId)` for the same room, which you did not intend. Logging the visit **is a separate process** from connecting. Write them as two separate Effects: +Mas imagine que você mais tarde adicione outra dependência a este Efeito que precisa restabelecer a conexão. Se este Efeito re-sincronizar, ele também chamará `logVisit(roomId)` para a mesma sala, o que você não pretendia. Registrar a visita **é um processo separado** de conectar. Escreva-os como dois Efeitos separados: ```js {2-4} function ChatRoom({ roomId }) { @@ -346,13 +346,13 @@ function ChatRoom({ roomId }) { } ``` -**Each Effect in your code should represent a separate and independent synchronization process.** +**Cada Efeito no seu código deve representar um processo de sincronização separado e independente.** -In the above example, deleting one Effect wouldn’t break the other Effect's logic. This is a good indication that they synchronize different things, and so it made sense to split them up. On the other hand, if you split up a cohesive piece of logic into separate Effects, the code may look "cleaner" but will be [more difficult to maintain.](/learn/you-might-not-need-an-effect#chains-of-computations) This is why you should think whether the processes are same or separate, not whether the code looks cleaner. +No exemplo acima, excluir um Efeito não quebraria a lógica do outro Efeito. Este é um bom indicativo de que eles sincronizam coisas diferentes, portanto, faz sentido dividi-los. Por outro lado, se você dividir um pedaço coeso de lógica em Efeitos separados, o código pode parecer "mais limpo", mas será [mais difícil de manter.](/learn/you-might-not-need-an-effect#chains-of-computations) Por isso, você deve pensar se os processos são iguais ou separados, não se o código parece mais limpo. -## Effects "react" to reactive values {/*effects-react-to-reactive-values*/} +## Efeitos "reagem" a valores reativos {/*effects-react-to-reactive-values*/} -Your Effect reads two variables (`serverUrl` and `roomId`), but you only specified `roomId` as a dependency: +Seu Efeito lê duas variáveis (`serverUrl` e `roomId`), mas você especificou apenas `roomId` como uma dependência: ```js {5,10} const serverUrl = 'https://localhost:1234'; @@ -369,32 +369,32 @@ function ChatRoom({ roomId }) { } ``` -Why doesn't `serverUrl` need to be a dependency? +Por que `serverUrl` não precisa ser uma dependência? -This is because the `serverUrl` never changes due to a re-render. It's always the same no matter how many times the component re-renders and why. Since `serverUrl` never changes, it wouldn't make sense to specify it as a dependency. After all, dependencies only do something when they change over time! +Isso acontece porque o `serverUrl` nunca muda devido a uma re-renderização. Ele é sempre o mesmo, não importa quantas vezes o componente é re-renderizado e por quê. Como o `serverUrl` nunca muda, não faria sentido especificá-lo como uma dependência. Afinal, as dependências só fazem algo quando mudam ao longo do tempo! -On the other hand, `roomId` may be different on a re-render. **Props, state, and other values declared inside the component are _reactive_ because they're calculated during rendering and participate in the React data flow.** +Por outro lado, `roomId` pode ser diferente em uma re-renderização. **Props, estados e outros valores declarados dentro do componente são _reativos_ porque são calculados durante a renderização e participam do fluxo de dados do React.** -If `serverUrl` was a state variable, it would be reactive. Reactive values must be included in dependencies: +Se `serverUrl` fosse uma variável de estado, seria reativa. Valores reativos devem ser incluídos nas dependências: ```js {2,5,10} -function ChatRoom({ roomId }) { // Props change over time - const [serverUrl, setServerUrl] = useState('https://localhost:1234'); // State may change over time +function ChatRoom({ roomId }) { // Props mudam ao longo do tempo + const [serverUrl, setServerUrl] = useState('https://localhost:1234'); // O estado pode mudar ao longo do tempo useEffect(() => { - const connection = createConnection(serverUrl, roomId); // Your Effect reads props and state + const connection = createConnection(serverUrl, roomId); // Seu Efeito lê props e estado connection.connect(); return () => { connection.disconnect(); }; - }, [roomId, serverUrl]); // So you tell React that this Effect "depends on" on props and state + }, [roomId, serverUrl]); // Então você diz ao React que este Efeito "depende de" props e estado // ... } ``` -By including `serverUrl` as a dependency, you ensure that the Effect re-synchronizes after it changes. +Incluindo `serverUrl` como uma dependência, você garante que o Efeito re-sincroniza após mudar. -Try changing the selected chat room or edit the server URL in this sandbox: +Tente mudar a sala de chat selecionada ou editar a URL do servidor neste sandbox: @@ -414,13 +414,13 @@ function ChatRoom({ roomId }) { return ( <> -

Welcome to the {roomId} room!

+

Bem-vindo à sala {roomId}!

); } @@ -430,7 +430,7 @@ export default function App() { return ( <> -

Welcome to the {roomId} room!

+

Bem-vindo à sala {roomId}!

); } @@ -629,7 +628,7 @@ export default function App() { return ( <>