diff --git a/src/content/learn/synchronizing-with-effects.md b/src/content/learn/synchronizing-with-effects.md
index 9ca109656..419f6a08d 100644
--- a/src/content/learn/synchronizing-with-effects.md
+++ b/src/content/learn/synchronizing-with-effects.md
@@ -1,97 +1,96 @@
---
-title: 'Synchronizing with Effects'
+title: 'Sincronizando com Efeitos'
---
-Some components need to synchronize with external systems. For example, you might want to control a non-React component based on the React state, set up a server connection, or send an analytics log when a component appears on the screen. *Effects* let you run some code after rendering so that you can synchronize your component with some system outside of React.
+Alguns componentes precisam se sincronizar com sistemas externos. Por exemplo, você pode querer controlar um componente que não é do React com base no estado do React, configurar uma conexão com o servidor ou enviar um log de análise quando um componente aparecer na tela. *Efeitos* permitem que você execute algum código após a renderização para que você possa sincronizar seu componente com algum sistema fora do React.
-- What Effects are
-- How Effects are different from events
-- How to declare an Effect in your component
-- How to skip re-running an Effect unnecessarily
-- Why Effects run twice in development and how to fix them
+- O que são Efeitos
+- Como os Efeitos diferem de eventos
+- Como declarar um Efeito em seu componente
+- Como evitar a reexecução desnecessária de um Efeito
+- Por que os Efeitos são executados duas vezes em desenvolvimento e como corrigir isso
-## What are Effects and how are they different from events? {/*what-are-effects-and-how-are-they-different-from-events*/}
+## O que são Efeitos e como eles diferem de eventos? {/*what-are-effects-and-how-are-they-different-from-events*/}
-Before getting to Effects, you need to be familiar with two types of logic inside React components:
+Antes de abordar os Efeitos, você precisa estar familiarizado com dois tipos de lógica dentro dos componentes do React:
-- **Rendering code** (introduced in [Describing the UI](/learn/describing-the-ui)) lives at the top level of your component. This is where you take the props and state, transform them, and return the JSX you want to see on the screen. [Rendering code must be pure.](/learn/keeping-components-pure) Like a math formula, it should only _calculate_ the result, but not do anything else.
+- **Código de renderização** (introduzido em [Descrevendo a UI](/learn/describing-the-ui)) vive no nível superior do seu componente. É aqui que você pega as props e o estado, os transforma e retorna o JSX que você quer ver na tela. [O código de renderização deve ser puro.](/learn/keeping-components-pure) Como uma fórmula matemática, ele deve apenas _calcular_ o resultado, mas não fazer nada mais.
-- **Event handlers** (introduced in [Adding Interactivity](/learn/adding-interactivity)) are nested functions inside your components that *do* things rather than just calculate them. An event handler might update an input field, submit an HTTP POST request to buy a product, or navigate the user to another screen. Event handlers contain ["side effects"](https://en.wikipedia.org/wiki/Side_effect_(computer_science)) (they change the program's state) caused by a specific user action (for example, a button click or typing).
+- **Manipuladores de eventos** (introduzidos em [Adicionando Interatividade](/learn/adding-interactivity)) são funções aninhadas dentro dos seus componentes que *fazem* coisas em vez de apenas calculá-las. Um manipulador de eventos pode atualizar um campo de entrada, enviar uma solicitação HTTP POST para comprar um produto ou navegar o usuário para outra tela. Manipuladores de eventos contêm ["efeitos colaterais"](https://en.wikipedia.org/wiki/Side_effect_(computer_science)) (eles mudam o estado do programa) causados por uma ação específica do usuário (por exemplo, um clique de botão ou digitação).
-Sometimes this isn't enough. Consider a `ChatRoom` component that must connect to the chat server whenever it's visible on the screen. Connecting to a server is not a pure calculation (it's a side effect) so it can't happen during rendering. However, there is no single particular event like a click that causes `ChatRoom` to be displayed.
+Às vezes, isso não é suficiente. Considere um componente `ChatRoom` que deve se conectar ao servidor de chat sempre que estiver visível na tela. Conectar-se a um servidor não é um cálculo puro (é um efeito colateral), então não pode acontecer durante a renderização. No entanto, não há um evento particular como um clique que cause a exibição do `ChatRoom`.
-***Effects* let you specify side effects that are caused by rendering itself, rather than by a particular event.** Sending a message in the chat is an *event* because it is directly caused by the user clicking a specific button. However, setting up a server connection is an *Effect* because it should happen no matter which interaction caused the component to appear. Effects run at the end of a [commit](/learn/render-and-commit) after the screen updates. This is a good time to synchronize the React components with some external system (like network or a third-party library).
+***Efeitos* permitem que você especifique efeitos colaterais que são causados pela própria renderização, em vez de por um evento particular.** Enviar uma mensagem no chat é um *evento* porque é causado diretamente pelo usuário ao clicar em um botão específico. No entanto, configurar uma conexão com o servidor é um *Efeito* porque deve acontecer não importando qual interação causou o aparecimento do componente. Efeitos são executados no final de um [compromisso](/learn/render-and-commit) após a atualização da tela. Este é um bom momento para sincronizar os componentes do React com algum sistema externo (como uma rede ou uma biblioteca de terceiros).
-Here and later in this text, capitalized "Effect" refers to the React-specific definition above, i.e. a side effect caused by rendering. To refer to the broader programming concept, we'll say "side effect".
+Aqui e mais adiante neste texto, "Efeito" com letra maiúscula refere-se à definição específica do React acima, ou seja, um efeito colateral causado pela renderização. Para referir-se ao conceito de programação mais amplo, diremos "efeito colateral".
+## Você pode não precisar de um Efeito {/*you-might-not-need-an-effect*/}
-## You might not need an Effect {/*you-might-not-need-an-effect*/}
+**Não se apresse para adicionar Efeitos aos seus componentes.** Lembre-se de que os Efeitos são normalmente usados para "sair" do seu código React e se sincronizar com algum sistema *externo*. Isso inclui APIs do navegador, widgets de terceiros, rede, e assim por diante. Se o seu Efeito apenas ajusta algum estado com base em outro estado, [você pode não precisar de um Efeito.](/learn/you-might-not-need-an-effect)
-**Don't rush to add Effects to your components.** Keep in mind that Effects are typically used to "step out" of your React code and synchronize with some *external* system. This includes browser APIs, third-party widgets, network, and so on. If your Effect only adjusts some state based on other state, [you might not need an Effect.](/learn/you-might-not-need-an-effect)
+## Como escrever um Efeito {/*how-to-write-an-effect*/}
-## How to write an Effect {/*how-to-write-an-effect*/}
+Para escrever um Efeito, siga estas três etapas:
-To write an Effect, follow these three steps:
+1. **Declare um Efeito.** Por padrão, seu Efeito será executado após cada [compromisso](/learn/render-and-commit).
+2. **Especifique as dependências do Efeito.** A maioria dos Efeitos deve apenas ser reexecutada *quando necessário* em vez de após cada renderização. Por exemplo, uma animação de aparecimento deve apenas ser acionada quando um componente aparecer. Conectar-se e desconectar-se de uma sala de chat deve acontecer apenas quando o componente aparecer e desaparecer, ou quando a sala de chat mudar. Você aprenderá a controlar isso especificando *dependências*.
+3. **Adicione limpeza se necessário.** Alguns Efeitos precisam especificar como parar, desfazer ou limpar o que estavam fazendo. Por exemplo, "conectar" precisa de "desconectar", "inscrever" precisa de "cancelar inscrição", e "buscar" precisa de "cancelar" ou "ignorar". Você aprenderá a fazer isso retornando uma *função de limpeza*.
-1. **Declare an Effect.** By default, your Effect will run after every [commit](/learn/render-and-commit).
-2. **Specify the Effect dependencies.** Most Effects should only re-run *when needed* rather than after every render. For example, a fade-in animation should only trigger when a component appears. Connecting and disconnecting to a chat room should only happen when the component appears and disappears, or when the chat room changes. You will learn how to control this by specifying *dependencies.*
-3. **Add cleanup if needed.** Some Effects need to specify how to stop, undo, or clean up whatever they were doing. For example, "connect" needs "disconnect", "subscribe" needs "unsubscribe", and "fetch" needs either "cancel" or "ignore". You will learn how to do this by returning a *cleanup function*.
+Vamos olhar para cada uma dessas etapas em detalhes.
-Let's look at each of these steps in detail.
+### Etapa 1: Declare um Efeito {/*step-1-declare-an-effect*/}
-### Step 1: Declare an Effect {/*step-1-declare-an-effect*/}
-
-To declare an Effect in your component, import the [`useEffect` Hook](/reference/react/useEffect) from React:
+Para declarar um Efeito em seu componente, importe o [`useEffect` Hook](/reference/react/useEffect) do React:
```js
import { useEffect } from 'react';
```
-Then, call it at the top level of your component and put some code inside your Effect:
+Em seguida, chame-o no nível superior do seu componente e coloque algum código dentro do seu Efeito:
```js {2-4}
function MyComponent() {
useEffect(() => {
- // Code here will run after *every* render
+ // O código aqui será executado após *cada* renderização
});
return
;
}
```
-Every time your component renders, React will update the screen *and then* run the code inside `useEffect`. In other words, **`useEffect` "delays" a piece of code from running until that render is reflected on the screen.**
+Toda vez que seu componente renderizar, o React atualizará a tela *e então* executará o código dentro de `useEffect`. Em outras palavras, **`useEffect` "atrasará" um trecho de código de ser executado até que aquela renderização seja refletida na tela.**
-Let's see how you can use an Effect to synchronize with an external system. Consider a `` React component. It would be nice to control whether it's playing or paused by passing an `isPlaying` prop to it:
+Vamos ver como você pode usar um Efeito para se sincronizar com um sistema externo. Considere um componente React ``. Seria bom controlar se está tocando ou pausado passando uma prop `isPlaying` para ele:
```js
;
```
-Your custom `VideoPlayer` component renders the built-in browser [``](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/video) tag:
+Seu componente personalizado `VideoPlayer` renderiza a tag `` incorporada do navegador:
```js
function VideoPlayer({ src, isPlaying }) {
- // TODO: do something with isPlaying
+ // TODO: faça algo com isPlaying
return ;
}
```
-However, the browser `` tag does not have an `isPlaying` prop. The only way to control it is to manually call the [`play()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/play) and [`pause()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/pause) methods on the DOM element. **You need to synchronize the value of `isPlaying` prop, which tells whether the video _should_ currently be playing, with calls like `play()` and `pause()`.**
+No entanto, a tag `` do navegador não possui uma prop `isPlaying`. A única maneira de controlá-la é chamar manualmente os métodos [`play()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/play) e [`pause()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/pause) no elemento do DOM. **Você precisa sincronizar o valor da prop `isPlaying`, que diz se o vídeo _deve_ estar tocando atualmente, com chamadas como `play()` e `pause()`.**
-We'll need to first [get a ref](/learn/manipulating-the-dom-with-refs) to the `` DOM node.
+Primeiro, precisamos [obter uma referência](/learn/manipulating-the-dom-with-refs) para o nó do DOM ``.
-You might be tempted to try to call `play()` or `pause()` during rendering, but that isn't correct:
+Você pode ser tentado a tentar chamar `play()` ou `pause()` durante a renderização, mas isso não está correto:
@@ -102,9 +101,9 @@ function VideoPlayer({ src, isPlaying }) {
const ref = useRef(null);
if (isPlaying) {
- ref.current.play(); // Calling these while rendering isn't allowed.
+ ref.current.play(); // Chamar isso durante a renderização não é permitido.
} else {
- ref.current.pause(); // Also, this crashes.
+ ref.current.pause(); // Além disso, isso causa falha.
}
return ;
@@ -115,7 +114,7 @@ export default function App() {
return (
<>
setIsPlaying(!isPlaying)}>
- {isPlaying ? 'Pause' : 'Play'}
+ {isPlaying ? 'Pausar' : 'Tocar'}
-The reason this code isn't correct is that it tries to do something with the DOM node during rendering. In React, [rendering should be a pure calculation](/learn/keeping-components-pure) of JSX and should not contain side effects like modifying the DOM.
+A razão pela qual esse código não está correto é que ele tenta fazer algo com o nó do DOM durante a renderização. No React, [a renderização deve ser uma cálculo puro](/learn/keeping-components-pure) de JSX e não deve conter efeitos colaterais como modificar o DOM.
-Moreover, when `VideoPlayer` is called for the first time, its DOM does not exist yet! There isn't a DOM node yet to call `play()` or `pause()` on, because React doesn't know what DOM to create until you return the JSX.
+Além disso, quando `VideoPlayer` é chamado pela primeira vez, seu DOM ainda não existe! Não há um nó do DOM para chamar `play()` ou `pause()`, porque o React não sabe qual DOM criar até você retornar o JSX.
-The solution here is to **wrap the side effect with `useEffect` to move it out of the rendering calculation:**
+A solução aqui é **envolver o efeito colateral com `useEffect` para movê-lo para fora do cálculo de renderização:**
```js {6,12}
import { useEffect, useRef } from 'react';
@@ -157,11 +156,11 @@ function VideoPlayer({ src, isPlaying }) {
}
```
-By wrapping the DOM update in an Effect, you let React update the screen first. Then your Effect runs.
+Ao envolver a atualização do DOM em um Efeito, você permite que o React atualize a tela primeiro. Então, seu Efeito é executado.
-When your `VideoPlayer` component renders (either the first time or if it re-renders), a few things will happen. First, React will update the screen, ensuring the `` tag is in the DOM with the right props. Then React will run your Effect. Finally, your Effect will call `play()` or `pause()` depending on the value of `isPlaying`.
+Quando seu componente `VideoPlayer` renderiza (seja pela primeira vez ou se ele re-renderiza), algumas coisas acontecerão. Primeiro, o React atualizará a tela, garantindo que a tag `` esteja no DOM com as props corretas. Em seguida, o React executará seu Efeito. Por fim, seu Efeito chamará `play()` ou `pause()` dependendo do valor de `isPlaying`.
-Press Play/Pause multiple times and see how the video player stays synchronized to the `isPlaying` value:
+Pressione Tocar/Pausar várias vezes e veja como o player de vídeo permanece sincronizado com o valor de `isPlaying`:
@@ -187,7 +186,7 @@ export default function App() {
return (
<>
setIsPlaying(!isPlaying)}>
- {isPlaying ? 'Pause' : 'Play'}
+ {isPlaying ? 'Pausar' : 'Tocar'}
-In this example, the "external system" you synchronized to React state was the browser media API. You can use a similar approach to wrap legacy non-React code (like jQuery plugins) into declarative React components.
+Neste exemplo, o "sistema externo" que você sincronizou com o estado do React foi a API de mídia do navegador. Você pode usar uma abordagem semelhante para envolver código legado não react (como plugins jQuery) em componentes declarativos do React.
-Note that controlling a video player is much more complex in practice. Calling `play()` may fail, the user might play or pause using the built-in browser controls, and so on. This example is very simplified and incomplete.
+Observe que controlar um player de vídeo é muito mais complexo na prática. Chamar `play()` pode falhar, o usuário pode tocar ou pausar usando os controles embutidos do navegador, e assim por diante. Este exemplo é muito simplificado e incompleto.
-By default, Effects run after *every* render. This is why code like this will **produce an infinite loop:**
+Por padrão, os Efeitos são executados após *cada* renderização. É por isso que códigos como este **produzirão um loop infinito:**
```js
const [count, setCount] = useState(0);
@@ -220,20 +219,20 @@ useEffect(() => {
});
```
-Effects run as a *result* of rendering. Setting state *triggers* rendering. Setting state immediately in an Effect is like plugging a power outlet into itself. The Effect runs, it sets the state, which causes a re-render, which causes the Effect to run, it sets the state again, this causes another re-render, and so on.
+Os Efeitos são executados como um *resultado* da renderização. Definir o estado *dispara* a renderização. Definir o estado imediatamente em um Efeito é como conectar um outlet na sua própria fonte de energia. O Efeito é executado, define o estado, que causa uma nova renderização, que faz com que o Efeito seja executado de novo, define o estado novamente, isso causa outra renderização, e assim por diante.
-Effects should usually synchronize your components with an *external* system. If there's no external system and you only want to adjust some state based on other state, [you might not need an Effect.](/learn/you-might-not-need-an-effect)
+Os Efeitos devem geralmente sincronizar seus componentes com um sistema *externo*. Se não há um sistema externo e você só quer ajustar algum estado com base em outro estado, [você pode não precisar de um Efeito.](/learn/you-might-not-need-an-effect)
-### Step 2: Specify the Effect dependencies {/*step-2-specify-the-effect-dependencies*/}
+### Etapa 2: Especificar as dependências do Efeito {/*step-2-specify-the-effect-dependencies*/}
-By default, Effects run after *every* render. Often, this is **not what you want:**
+Por padrão, os Efeitos são executados após *cada* renderização. Muitas vezes, isso é **não o que você deseja:**
-- Sometimes, it's slow. Synchronizing with an external system is not always instant, so you might want to skip doing it unless it's necessary. For example, you don't want to reconnect to the chat server on every keystroke.
-- Sometimes, it's wrong. For example, you don't want to trigger a component fade-in animation on every keystroke. The animation should only play once when the component appears for the first time.
+- Às vezes, é lento. Sincronizar com um sistema externo nem sempre é instantâneo, então você pode querer pular a execução a menos que seja necessário. Por exemplo, você não deseja reconectar ao servidor de chat a cada tecla pressionada.
+- Às vezes, está errado. Por exemplo, você não deseja acionar uma animação de desvanecimento do componente em cada tecla pressionada. A animação deve tocar apenas uma vez quando o componente aparecer pela primeira vez.
-To demonstrate the issue, here is the previous example with a few `console.log` calls and a text input that updates the parent component's state. Notice how typing causes the Effect to re-run:
+Para demonstrar o problema, aqui está o exemplo anterior com alguns `console.log` e um campo de texto que atualiza o estado do componente pai. Note como digitar causa a reexecução do Efeito:
@@ -245,10 +244,10 @@ function VideoPlayer({ src, isPlaying }) {
useEffect(() => {
if (isPlaying) {
- console.log('Calling video.play()');
+ console.log('Chamando video.play()');
ref.current.play();
} else {
- console.log('Calling video.pause()');
+ console.log('Chamando video.pause()');
ref.current.pause();
}
});
@@ -263,7 +262,7 @@ export default function App() {
<>
setText(e.target.value)} />
setIsPlaying(!isPlaying)}>
- {isPlaying ? 'Pause' : 'Play'}
+ {isPlaying ? 'Pausar' : 'Tocar'}
-You can tell React to **skip unnecessarily re-running the Effect** by specifying an array of *dependencies* as the second argument to the `useEffect` call. Start by adding an empty `[]` array to the above example on line 14:
+Você pode dizer ao React para **pular a reexecução desnecessária do Efeito** especificando um array de *dependências* como segundo argumento para a chamada `useEffect`. Comece adicionando um array vazio `[]` ao exemplo acima na linha 14:
```js {3}
useEffect(() => {
@@ -289,7 +288,7 @@ You can tell React to **skip unnecessarily re-running the Effect** by specifying
}, []);
```
-You should see an error saying `React Hook useEffect has a missing dependency: 'isPlaying'`:
+Você deve ver um erro dizendo `O Hook React useEffect tem uma dependência ausente: 'isPlaying'`:
@@ -301,13 +300,13 @@ function VideoPlayer({ src, isPlaying }) {
useEffect(() => {
if (isPlaying) {
- console.log('Calling video.play()');
+ console.log('Chamando video.play()');
ref.current.play();
} else {
- console.log('Calling video.pause()');
+ console.log('Chamando video.pause()');
ref.current.pause();
}
- }, []); // This causes an error
+ }, []); // Isso causa um erro
return ;
}
@@ -319,7 +318,7 @@ export default function App() {
<>
setText(e.target.value)} />
setIsPlaying(!isPlaying)}>
- {isPlaying ? 'Pause' : 'Play'}
+ {isPlaying ? 'Pausar' : 'Tocar'}
-The problem is that the code inside of your Effect *depends on* the `isPlaying` prop to decide what to do, but this dependency was not explicitly declared. To fix this issue, add `isPlaying` to the dependency array:
+O problema é que o código dentro do seu Efeito *depende de* a prop `isPlaying` para decidir o que fazer, mas essa dependência não foi explicitamente declarada. Para corrigir esse problema, adicione `isPlaying` ao array de dependências:
```js {2,7}
useEffect(() => {
- if (isPlaying) { // It's used here...
+ if (isPlaying) { // Está sendo usado aqui...
// ...
} else {
// ...
}
- }, [isPlaying]); // ...so it must be declared here!
+ }, [isPlaying]); // ...então deve ser declarado aqui!
```
-Now all dependencies are declared, so there is no error. Specifying `[isPlaying]` as the dependency array tells React that it should skip re-running your Effect if `isPlaying` is the same as it was during the previous render. With this change, typing into the input doesn't cause the Effect to re-run, but pressing Play/Pause does:
+Agora todas as dependências estão declaradas, então não há erro. Especificar `[isPlaying]` como o array de dependências diz ao React que ele deve pular a reexecução do seu Efeito se `isPlaying` for o mesmo que era durante a renderização anterior. Com essa mudança, digitar no campo de entrada não causa a reexecução do Efeito, mas pressionar Tocar/Pausar faz:
@@ -361,10 +360,10 @@ function VideoPlayer({ src, isPlaying }) {
useEffect(() => {
if (isPlaying) {
- console.log('Calling video.play()');
+ console.log('Chamando video.play()');
ref.current.play();
} else {
- console.log('Calling video.pause()');
+ console.log('Chamando video.pause()');
ref.current.pause();
}
}, [isPlaying]);
@@ -379,7 +378,7 @@ export default function App() {
<>
setText(e.target.value)} />
setIsPlaying(!isPlaying)}>
- {isPlaying ? 'Pause' : 'Play'}
+ {isPlaying ? 'Pausar' : 'Tocar'}
-The dependency array can contain multiple dependencies. React will only skip re-running the Effect if *all* of the dependencies you specify have exactly the same values as they had during the previous render. React compares the dependency values using the [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison. See the [`useEffect` reference](/reference/react/useEffect#reference) for details.
+O array de dependências pode conter múltiplas dependências. O React só pulará a reexecução do Efeito se *todas* as dependências que você especificou tiverem exatamente os mesmos valores que tinham durante a renderização anterior. O React compara os valores das dependências usando a comparação [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). Veja a [referência de `useEffect`](/reference/react/useEffect#reference) para mais detalhes.
-**Notice that you can't "choose" your dependencies.** You will get a lint error if the dependencies you specified don't match what React expects based on the code inside your Effect. This helps catch many bugs in your code. If you don't want some code to re-run, [*edit the Effect code itself* to not "need" that dependency.](/learn/lifecycle-of-reactive-effects#what-to-do-when-you-dont-want-to-re-synchronize)
+**Observe que você não pode "escolher" suas dependências.** Você receberá um erro de lint se as dependências que você especificou não corresponderem ao que o React espera com base no código dentro do seu Efeito. Isso ajuda a detectar muitos bugs no seu código. Se você não quiser que algum código seja reexecutado, [*edite o próprio código do Efeito* para não "precisar" daquela dependência.](/learn/lifecycle-of-reactive-effects#what-to-do-when-you-dont-want-to-re-synchronize)
-The behaviors without the dependency array and with an *empty* `[]` dependency array are different:
+Os comportamentos sem o array de dependências e com um array de dependências *vazio* `[]` são diferentes:
```js {3,7,11}
useEffect(() => {
- // This runs after every render
+ // Isso é executado após cada renderização
});
useEffect(() => {
- // This runs only on mount (when the component appears)
+ // Isso é executado apenas na montagem (quando o componente aparece)
}, []);
useEffect(() => {
- // This runs on mount *and also* if either a or b have changed since the last render
+ // Isso é executado na montagem *e também* se a ou b mudaram desde a última renderização
}, [a, b]);
```
-We'll take a close look at what "mount" means in the next step.
+Vamos examinar de perto o que "montagem" significa na próxima etapa.
-#### Why was the ref omitted from the dependency array? {/*why-was-the-ref-omitted-from-the-dependency-array*/}
+#### Por que a referência foi omitida do array de dependência? {/*why-was-the-ref-omitted-from-the-dependency-array*/}
-This Effect uses _both_ `ref` and `isPlaying`, but only `isPlaying` is declared as a dependency:
+Este Efeito usa _tanto_ `ref` quanto `isPlaying`, mas apenas `isPlaying` é declarado como uma dependência:
```js {9}
function VideoPlayer({ src, isPlaying }) {
@@ -441,7 +440,7 @@ function VideoPlayer({ src, isPlaying }) {
}, [isPlaying]);
```
-This is because the `ref` object has a *stable identity:* React guarantees [you'll always get the same object](/reference/react/useRef#returns) from the same `useRef` call on every render. It never changes, so it will never by itself cause the Effect to re-run. Therefore, it does not matter whether you include it or not. Including it is fine too:
+Isso se deve ao fato de que o objeto `ref` tem uma *identidade estável:* O React garante [que você sempre receberá o mesmo objeto](/reference/react/useRef#returns) da mesma chamada de `useRef` em cada renderização. Ele nunca muda, portanto, nunca causará por si só a reexecução do Efeito. Assim, não importa se você inclui ou não. Incluir também é aceitável:
```js {9}
function VideoPlayer({ src, isPlaying }) {
@@ -455,17 +454,17 @@ function VideoPlayer({ src, isPlaying }) {
}, [isPlaying, ref]);
```
-The [`set` functions](/reference/react/useState#setstate) returned by `useState` also have stable identity, so you will often see them omitted from the dependencies too. If the linter lets you omit a dependency without errors, it is safe to do.
+As funções [`set`](https://reference/react/useState#setstate) retornadas por `useState` também têm identidade estável, portanto você verá frequentemente elas omitidas das dependências também. Se o linter permitir que você omita uma dependência sem erros, é seguro fazê-lo.
-Omitting always-stable dependencies only works when the linter can "see" that the object is stable. For example, if `ref` was passed from a parent component, you would have to specify it in the dependency array. However, this is good because you can't know whether the parent component always passes the same ref, or passes one of several refs conditionally. So your Effect _would_ depend on which ref is passed.
+Omitir dependências sempre estáveis funciona apenas quando o linter pode "ver" que o objeto é estável. Por exemplo, se `ref` fosse passado de um componente pai, você teria que especificá-lo no array de dependências. No entanto, isso é bom porque você não pode saber se o componente pai sempre passa a mesma referência, ou passa uma de várias referências condicionalmente. Assim, seu Efeito _dependeria_ de qual referência é passada.
-### Step 3: Add cleanup if needed {/*step-3-add-cleanup-if-needed*/}
+### Etapa 3: Adicionar limpeza se necessário {/*step-3-add-cleanup-if-needed*/}
-Consider a different example. You're writing a `ChatRoom` component that needs to connect to the chat server when it appears. You are given a `createConnection()` API that returns an object with `connect()` and `disconnect()` methods. How do you keep the component connected while it is displayed to the user?
+Considere um exemplo diferente. Você está escrevendo um componente `ChatRoom` que precisa se conectar ao servidor de chat quando aparecer. Você tem uma API `createConnection()` que retorna um objeto com métodos `connect()` e `disconnect()`. Como você mantém o componente conectado enquanto ele é exibido para o usuário?
-Start by writing the Effect logic:
+Comece escrevendo a lógica do Efeito:
```js
useEffect(() => {
@@ -474,7 +473,7 @@ useEffect(() => {
});
```
-It would be slow to connect to the chat after every re-render, so you add the dependency array:
+Seria lento conectar-se ao chat após cada re-renderização, então você adiciona o array de dependências:
```js {4}
useEffect(() => {
@@ -483,9 +482,9 @@ useEffect(() => {
}, []);
```
-**The code inside the Effect does not use any props or state, so your dependency array is `[]` (empty). This tells React to only run this code when the component "mounts", i.e. appears on the screen for the first time.**
+**O código dentro do Efeito não usa nenhuma prop ou estado, então seu array de dependências é `[]` (vazio). Isso diz ao React para executar esse código apenas quando o componente "monta", ou seja, quando aparece na tela pela primeira vez.**
-Let's try running this code:
+Vamos tentar executar esse código:
@@ -498,19 +497,19 @@ export default function ChatRoom() {
const connection = createConnection();
connection.connect();
}, []);
- return Welcome to the chat! ;
+ return Bem-vindo ao chat! ;
}
```
```js src/chat.js
export function createConnection() {
- // A real implementation would actually connect to the server
+ // Uma implementação real realmente se conectaria ao servidor
return {
connect() {
- console.log('✅ Connecting...');
+ console.log('✅ Conectando...');
},
disconnect() {
- console.log('❌ Disconnected.');
+ console.log('❌ Desconectado.');
}
};
}
@@ -522,15 +521,15 @@ input { display: block; margin-bottom: 20px; }
-This Effect only runs on mount, so you might expect `"✅ Connecting..."` to be printed once in the console. **However, if you check the console, `"✅ Connecting..."` gets printed twice. Why does it happen?**
+Esse Efeito só é executado na montagem, então você pode esperar que `"✅ Conectando..."` seja impresso uma vez no console. **No entanto, se você verificar o console, `"✅ Conectando..."` é impresso duas vezes. Por que isso acontece?**
-Imagine the `ChatRoom` component is a part of a larger app with many different screens. The user starts their journey on the `ChatRoom` page. The component mounts and calls `connection.connect()`. Then imagine the user navigates to another screen--for example, to the Settings page. The `ChatRoom` component unmounts. Finally, the user clicks Back and `ChatRoom` mounts again. This would set up a second connection--but the first connection was never destroyed! As the user navigates across the app, the connections would keep piling up.
+Imagine que o componente `ChatRoom` é parte de um aplicativo maior com muitas telas diferentes. O usuário começa sua jornada na página `ChatRoom`. O componente monta e chama `connection.connect()`. Em seguida, imagine que o usuário navega para outra tela -- por exemplo, para a página de Configurações. O componente `ChatRoom` é desmontado. Finalmente, o usuário clica em Voltar e `ChatRoom` monta novamente. Isso configuraria uma segunda conexão--mas a primeira conexão nunca foi destruída! À medida que o usuário navega pelo aplicativo, as conexões continuariam se acumulando.
-Bugs like this are easy to miss without extensive manual testing. To help you spot them quickly, in development React remounts every component once immediately after its initial mount.
+Erros como esse são fáceis de perder sem testes manuais extensivos. Para ajudá-lo a detectá-los rapidamente, no desenvolvimento, o React remonta cada componente uma vez imediatamente após sua montagem inicial.
-Seeing the `"✅ Connecting..."` log twice helps you notice the real issue: your code doesn't close the connection when the component unmounts.
+Ver a mensagem `"✅ Conectando..."` ser impressa duas vezes ajuda você a perceber o problema real: seu código não fecha a conexão quando o componente desmonta.
-To fix the issue, return a *cleanup function* from your Effect:
+Para corrigir o problema, retorne uma *função de limpeza* do seu Efeito:
```js {4-6}
useEffect(() => {
@@ -542,7 +541,7 @@ To fix the issue, return a *cleanup function* from your Effect:
}, []);
```
-React will call your cleanup function each time before the Effect runs again, and one final time when the component unmounts (gets removed). Let's see what happens when the cleanup function is implemented:
+O React chamará sua função de limpeza toda vez que o Efeito for executado novamente, e uma última vez quando o componente for desmontado (removido). Vamos ver o que acontece quando a função de limpeza é implementada:
@@ -556,19 +555,19 @@ export default function ChatRoom() {
connection.connect();
return () => connection.disconnect();
}, []);
- return Welcome to the chat! ;
+ return Bem-vindo ao chat! ;
}
```
```js src/chat.js
export function createConnection() {
- // A real implementation would actually connect to the server
+ // Uma implementação real realmente se conectaria ao servidor
return {
connect() {
- console.log('✅ Connecting...');
+ console.log('✅ Conectando...');
},
disconnect() {
- console.log('❌ Disconnected.');
+ console.log('❌ Desconectado.');
}
};
}
@@ -580,34 +579,34 @@ input { display: block; margin-bottom: 20px; }
-Now you get three console logs in development:
+Agora você obterá três logs no console no desenvolvimento:
-1. `"✅ Connecting..."`
-2. `"❌ Disconnected."`
-3. `"✅ Connecting..."`
+1. `"✅ Conectando..."`
+2. `"❌ Desconectado."`
+3. `"✅ Conectando..."`
-**This is the correct behavior in development.** By remounting your component, React verifies that navigating away and back would not break your code. Disconnecting and then connecting again is exactly what should happen! When you implement the cleanup well, there should be no user-visible difference between running the Effect once vs running it, cleaning it up, and running it again. There's an extra connect/disconnect call pair because React is probing your code for bugs in development. This is normal--don't try to make it go away!
+**Este é o comportamento correto em desenvolvimento.** Remontando seu componente, o React verifica que navegar para longe e voltar não quebraria seu código. Desconectar e depois conectar novamente é exatamente o que deve acontecer! Quando você implementar a limpeza corretamente, não deve haver diferença visível para o usuário entre executar o Efeito uma vez e executá-lo, limpá-lo e executá-lo novamente. Há um par extra de chamadas de conectar/desconectar porque o React está testando seu código em busca de bugs em desenvolvimento. Isso é normal--não tente fazê-lo desaparecer!
-**In production, you would only see `"✅ Connecting..."` printed once.** Remounting components only happens in development to help you find Effects that need cleanup. You can turn off [Strict Mode](/reference/react/StrictMode) to opt out of the development behavior, but we recommend keeping it on. This lets you find many bugs like the one above.
+**Na produção, você veria apenas `"✅ Conectando..."` impresso uma vez.** A remontagem de componentes só acontece no desenvolvimento para ajudá-lo a encontrar Efeitos que precisam de limpeza. Você pode desligar o [Modo Estrito](/reference/react/StrictMode) para optar por não participar do comportamento de desenvolvimento, mas recomendamos que você mantenha-o ativado. Isso permite que você encontre muitos erros como o acima.
-## How to handle the Effect firing twice in development? {/*how-to-handle-the-effect-firing-twice-in-development*/}
+## Como lidar com a execução do Efeito duas vezes em desenvolvimento? {/*how-to-handle-the-effect-firing-twice-in-development*/}
-React intentionally remounts your components in development to find bugs like in the last example. **The right question isn't "how to run an Effect once", but "how to fix my Effect so that it works after remounting".**
+O React intencionalmente remonta seus componentes em desenvolvimento para encontrar erros, como no exemplo anterior. **A pergunta certa não é "como executar um Efeito uma vez", mas "como corrigir meu Efeito para que funcione após a remontagem".**
-Usually, the answer is to implement the cleanup function. The cleanup function should stop or undo whatever the Effect was doing. The rule of thumb is that the user shouldn't be able to distinguish between the Effect running once (as in production) and a _setup → cleanup → setup_ sequence (as you'd see in development).
+Normalmente, a resposta é implementar a função de limpeza. A função de limpeza deve parar ou desfazer o que o Efeito estava fazendo. A regra geral é que o usuário não deve ser capaz de distinguir entre o Efeito sendo executado uma vez (como na produção) e uma sequência de _configuração → limpeza → configuração_ (como você veria em desenvolvimento).
-Most of the Effects you'll write will fit into one of the common patterns below.
+A maioria dos Efeitos que você escreverá se encaixará em um dos padrões comuns abaixo.
-#### Don't use refs to prevent Effects from firing {/*dont-use-refs-to-prevent-effects-from-firing*/}
+#### Não use refs para impedir que Efeitos sejam executados {/*dont-use-refs-to-prevent-effects-from-firing*/}
-A common pitfall for preventing Effects firing twice in development is to use a `ref` to prevent the Effect from running more than once. For example, you could "fix" the above bug with a `useRef`:
+Uma armadilha comum para impedir que os Efeitos sejam executados duas vezes em desenvolvimento é usar uma `ref` para evitar que o Efeito seja executado mais de uma vez. Por exemplo, você poderia "corrigir" o erro acima com um `useRef`:
```js {1,3-4}
const connectionRef = useRef(null);
useEffect(() => {
- // 🚩 This wont fix the bug!!!
+ // 🚩 Isso não irá corrigir o bug!!!
if (!connectionRef.current) {
connectionRef.current = createConnection();
connectionRef.current.connect();
@@ -615,19 +614,19 @@ A common pitfall for preventing Effects firing twice in development is to use a
}, []);
```
-This makes it so you only see `"✅ Connecting..."` once in development, but it doesn't fix the bug.
+Isso faz com que você veja apenas `"✅ Conectando..."` uma vez em desenvolvimento, mas não corrige o erro.
-When the user navigates away, the connection still isn't closed and when they navigate back, a new connection is created. As the user navigates across the app, the connections would keep piling up, the same as it would before the "fix".
+Quando o usuário navega para longe, a conexão ainda não é fechada e quando ele navega de volta, uma nova conexão é criada. À medida que o usuário navega pelo aplicativo, as conexões continuariam se acumulando, assim como aconteceria antes da "correção".
-To fix the bug, it is not enough to just make the Effect run once. The effect needs to work after re-mounting, which means the connection needs to be cleaned up like in the solution above.
+Para corrigir o bug, não basta apenas fazer o Efeito ser executado uma vez. O efeito precisa funcionar após a remontagem, o que significa que a conexão precisa ser limpa como na solução acima.
-See the examples below for how to handle common patterns.
+Veja os exemplos abaixo para como lidar com padrões comuns.
-### Controlling non-React widgets {/*controlling-non-react-widgets*/}
+### Controlando widgets não-React {/*controlling-non-react-widgets*/}
-Sometimes you need to add UI widgets that aren't written to React. For example, let's say you're adding a map component to your page. It has a `setZoomLevel()` method, and you'd like to keep the zoom level in sync with a `zoomLevel` state variable in your React code. Your Effect would look similar to this:
+Às vezes, você precisa adicionar widgets de UI que não foram escritos para o React. Por exemplo, digamos que você está adicionando um componente de mapa à sua página. Ele tem um método `setZoomLevel()`, e você gostaria de manter o nível de zoom sincronizado com uma variável de estado `zoomLevel` em seu código React. Seu Efeito seria semelhante a isto:
```js
useEffect(() => {
@@ -636,9 +635,9 @@ useEffect(() => {
}, [zoomLevel]);
```
-Note that there is no cleanup needed in this case. In development, React will call the Effect twice, but this is not a problem because calling `setZoomLevel` twice with the same value does not do anything. It may be slightly slower, but this doesn't matter because it won't remount needlessly in production.
+Observe que não há necessidade de limpeza neste caso. No desenvolvimento, o React chamará o Efeito duas vezes, mas isso não é um problema pois chamar `setZoomLevel` duas vezes com o mesmo valor não faz nada. Pode ser um pouco mais lento, mas isso não importa pois não irá remontar desnecessariamente na produção.
-Some APIs may not allow you to call them twice in a row. For example, the [`showModal`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLDialogElement/showModal) method of the built-in [``](https://developer.mozilla.org/en-US/docs/Web/API/HTMLDialogElement) element throws if you call it twice. Implement the cleanup function and make it close the dialog:
+Algumas APIs podem não permitir que você as chame duas vezes em sequência. Por exemplo, o método [`showModal`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLDialogElement/showModal) do elemento `` embutido [https://developer.mozilla.org/en-US/docs/Web/API/HTMLDialogElement] lançará um erro se você o chamar duas vezes. Implemente a função de limpeza e faça-a fechar o diálogo:
```js {4}
useEffect(() => {
@@ -648,11 +647,11 @@ useEffect(() => {
}, []);
```
-In development, your Effect will call `showModal()`, then immediately `close()`, and then `showModal()` again. This has the same user-visible behavior as calling `showModal()` once, as you would see in production.
+No desenvolvimento, seu Efeito chamará `showModal()`, em seguida, imediatamente `close()`, e então `showModal()` novamente. Isso tem o mesmo comportamento visível para o usuário que chamar `showModal()` uma vez, como você faria na produção.
-### Subscribing to events {/*subscribing-to-events*/}
+### Inscrevendo-se em eventos {/*subscribing-to-events*/}
-If your Effect subscribes to something, the cleanup function should unsubscribe:
+Se seu Efeito se inscrever em algo, a função de limpeza deve cancelar a inscrição:
```js {6}
useEffect(() => {
@@ -664,27 +663,27 @@ useEffect(() => {
}, []);
```
-In development, your Effect will call `addEventListener()`, then immediately `removeEventListener()`, and then `addEventListener()` again with the same handler. So there would be only one active subscription at a time. This has the same user-visible behavior as calling `addEventListener()` once, as in production.
+No desenvolvimento, seu Efeito chamará `addEventListener()`, em seguida, imediatamente `removeEventListener()`, e então `addEventListener()` novamente com o mesmo manipulador. Assim, haveria apenas uma assinatura ativa de cada vez. Isso tem o mesmo comportamento visível para o usuário que chamar `addEventListener()` uma vez, como na produção.
-### Triggering animations {/*triggering-animations*/}
+### Acionando animações {/*triggering-animations*/}
-If your Effect animates something in, the cleanup function should reset the animation to the initial values:
+Se seu Efeito anima algo, a função de limpeza deve redefinir a animação para os valores iniciais:
```js {4-6}
useEffect(() => {
const node = ref.current;
- node.style.opacity = 1; // Trigger the animation
+ node.style.opacity = 1; // Aciona a animação
return () => {
- node.style.opacity = 0; // Reset to the initial value
+ node.style.opacity = 0; // Redefinir para o valor inicial
};
}, []);
```
-In development, opacity will be set to `1`, then to `0`, and then to `1` again. This should have the same user-visible behavior as setting it to `1` directly, which is what would happen in production. If you use a third-party animation library with support for tweening, your cleanup function should reset the timeline to its initial state.
+No desenvolvimento, a opacidade será definida como `1`, em seguida, `0`, e então `1` novamente. Isso deve ter o mesmo comportamento visível para o usuário que definir diretamente para `1`, que é o que aconteceria na produção. Se você usar uma biblioteca de animação de terceiros com suporte para animações gradativas, sua função de limpeza deve redefinir a linha do tempo para seu estado inicial.
-### Fetching data {/*fetching-data*/}
+### Buscando dados {/*fetching-data*/}
-If your Effect fetches something, the cleanup function should either [abort the fetch](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) or ignore its result:
+Se seu Efeito busca algo, a função de limpeza deve ou [abortar a busca](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) ou ignorar seu resultado:
```js {2,6,13-15}
useEffect(() => {
@@ -705,11 +704,11 @@ useEffect(() => {
}, [userId]);
```
-You can't "undo" a network request that already happened, but your cleanup function should ensure that the fetch that's _not relevant anymore_ does not keep affecting your application. If the `userId` changes from `'Alice'` to `'Bob'`, cleanup ensures that the `'Alice'` response is ignored even if it arrives after `'Bob'`.
+Você não pode "desfazer" uma solicitação de rede que já ocorreu, mas sua função de limpeza deve garantir que a busca que *não é mais relevante* não continue afetando sua aplicação. Se o `userId` mudar de `'Alice'` para `'Bob'`, a limpeza garante que a resposta de `'Alice'` seja ignorada mesmo que chegue após `'Bob'`.
-**In development, you will see two fetches in the Network tab.** There is nothing wrong with that. With the approach above, the first Effect will immediately get cleaned up so its copy of the `ignore` variable will be set to `true`. So even though there is an extra request, it won't affect the state thanks to the `if (!ignore)` check.
+**No desenvolvimento, você verá duas buscas na aba de Rede.** Não há nada de errado com isso. Com a abordagem acima, o primeiro Efeito será imediatamente limpo, de modo que sua cópia da variável `ignore` será definida como `true`. Portanto, mesmo que haja uma solicitação extra, ela não afetará o estado graças à checagem `if (!ignore)`.
-**In production, there will only be one request.** If the second request in development is bothering you, the best approach is to use a solution that deduplicates requests and caches their responses between components:
+**Na produção, haverá apenas uma solicitação.** Se a segunda solicitação no desenvolvimento estiver incomodando você, a melhor abordagem é usar uma solução que deduplica solicitações e registra suas respostas entre os componentes:
```js
function TodoList() {
@@ -717,50 +716,50 @@ function TodoList() {
// ...
```
-This will not only improve the development experience, but also make your application feel faster. For example, the user pressing the Back button won't have to wait for some data to load again because it will be cached. You can either build such a cache yourself or use one of the many alternatives to manual fetching in Effects.
+Isso não apenas melhorará a experiência de desenvolvimento, mas também fará seu aplicativo parecer mais rápido. Por exemplo, o usuário pressionando o botão Voltar não terá que esperar que alguns dados sejam carregados novamente porque eles estarão em cache. Você pode construir tal cache você mesmo ou usar uma das muitas alternativas para busca manual em Efeitos.
-#### What are good alternatives to data fetching in Effects? {/*what-are-good-alternatives-to-data-fetching-in-effects*/}
+#### Quais são boas alternativas para busca de dados em Efeitos? {/*what-are-good-alternatives-to-data-fetching-in-effects*/}
-Writing `fetch` calls inside Effects is a [popular way to fetch data](https://www.robinwieruch.de/react-hooks-fetch-data/), especially in fully client-side apps. This is, however, a very manual approach and it has significant downsides:
+Escrever chamadas `fetch` dentro de Efeitos é uma [maneira popular de buscar dados](https://www.robinwieruch.de/react-hooks-fetch-data/), especialmente em aplicativos totalmente do lado do cliente. No entanto, esta é uma abordagem muito manual e tem desvantagens significativas:
-- **Effects don't run on the server.** This means that the initial server-rendered HTML will only include a loading state with no data. The client computer will have to download all JavaScript and render your app only to discover that now it needs to load the data. This is not very efficient.
-- **Fetching directly in Effects makes it easy to create "network waterfalls".** You render the parent component, it fetches some data, renders the child components, and then they start fetching their data. If the network is not very fast, this is significantly slower than fetching all data in parallel.
-- **Fetching directly in Effects usually means you don't preload or cache data.** For example, if the component unmounts and then mounts again, it would have to fetch the data again.
-- **It's not very ergonomic.** There's quite a bit of boilerplate code involved when writing `fetch` calls in a way that doesn't suffer from bugs like [race conditions.](https://maxrozen.com/race-conditions-fetching-data-react-with-useeffect)
+- **Os Efeitos não são executados no servidor.** Isso significa que o HTML inicial renderizado no servidor incluirá apenas um estado de carregamento sem dados. O computador do cliente terá que baixar todo o JavaScript e renderizar seu aplicativo apenas para descobrir que agora precisa carregar os dados. Isso não é muito eficiente.
+- **Buscar diretamente em Efeitos torna fácil criar "cachoeiras de rede".** Você renderiza o componente pai, busca alguns dados, renderiza os componentes filhos, e então eles começam a buscar seus dados. Se a rede não for muito rápida, isso é significativamente mais lento do que buscar todos os dados em paralelo.
+- **Buscar diretamente em Efeitos geralmente significa que você não pré-carrega ou armazena dados em cache.** Por exemplo, se o componente desmonta e depois é montado novamente, ele teria que buscar os dados novamente.
+- **Não é muito ergonômico.** Há bastante código de boilerplate envolvido ao escrever chamadas `fetch` de uma maneira que não sofra com bugs como [condições de corrida.](https://maxrozen.com/race-conditions-fetching-data-react-with-useeffect)
-This list of downsides is not specific to React. It applies to fetching data on mount with any library. Like with routing, data fetching is not trivial to do well, so we recommend the following approaches:
+Essa lista de desvantagens não é específica do React. Ela se aplica a buscar dados na montagem com qualquer biblioteca. Como com roteamento, a busca de dados não é trivial de fazer bem, portanto, recomendamos as seguintes abordagens:
-- **If you use a [framework](/learn/start-a-new-react-project#production-grade-react-frameworks), use its built-in data fetching mechanism.** Modern React frameworks have integrated data fetching mechanisms that are efficient and don't suffer from the above pitfalls.
-- **Otherwise, consider using or building a client-side cache.** Popular open source solutions include [React Query](https://tanstack.com/query/latest), [useSWR](https://swr.vercel.app/), and [React Router 6.4+.](https://beta.reactrouter.com/en/main/start/overview) You can build your own solution too, in which case you would use Effects under the hood, but add logic for deduplicating requests, caching responses, and avoiding network waterfalls (by preloading data or hoisting data requirements to routes).
+- **Se você usar um [framework](/learn/start-a-new-react-project#production-grade-react-frameworks), use seu mecanismo de busca de dados embutido.** Frameworks modernos do React têm mecanismos de busca de dados integrados que são eficientes e não sofrem com as desvantagens acima.
+- **Caso contrário, considere usar ou construir um cache do lado do cliente.** Soluções populares de código aberto incluem [React Query](https://tanstack.com/query/latest), [useSWR](https://swr.vercel.app/), e [React Router 6.4+.](https://beta.reactrouter.com/en/main/start/overview) Você também pode construir sua própria solução, caso em que você usaria Efeitos no fundo, mas adicionaria lógica para deduplicar solicitações, armazenar respostas em cache e evitar cachoeiras de rede (pré-carregando dados ou erguer requisitos de dados para rotas).
-You can continue fetching data directly in Effects if neither of these approaches suit you.
+Você pode continuar buscando dados diretamente em Efeitos se nenhuma dessas abordagens servir para você.
-### Sending analytics {/*sending-analytics*/}
+### Enviando análises {/*sending-analytics*/}
-Consider this code that sends an analytics event on the page visit:
+Considere este código que envia um evento de análise na visita à página:
```js
useEffect(() => {
- logVisit(url); // Sends a POST request
+ logVisit(url); // Envia uma solicitação POST
}, [url]);
```
-In development, `logVisit` will be called twice for every URL, so you might be tempted to try to fix that. **We recommend keeping this code as is.** Like with earlier examples, there is no *user-visible* behavior difference between running it once and running it twice. From a practical point of view, `logVisit` should not do anything in development because you don't want the logs from the development machines to skew the production metrics. Your component remounts every time you save its file, so it logs extra visits in development anyway.
+No desenvolvimento, `logVisit` será chamado duas vezes para cada URL, então você pode ser tentado a tentar corrigir isso. **Recomendamos manter esse código como está.** Como em exemplos anteriores, não há diferença de *comportamento visível para o usuário* entre executá-lo uma vez e executá-lo duas vezes. Do ponto de vista prático, `logVisit` não deve fazer nada em desenvolvimento porque você não quer que os logs das máquinas de desenvolvimento deformem as métricas de produção. Seu componente remonta toda vez que você salva seu arquivo, então ele registra visitas extras em desenvolvimento de qualquer maneira.
-**In production, there will be no duplicate visit logs.**
+**Na produção, não haverá logs de visita duplicados.**
-To debug the analytics events you're sending, you can deploy your app to a staging environment (which runs in production mode) or temporarily opt out of [Strict Mode](/reference/react/StrictMode) and its development-only remounting checks. You may also send analytics from the route change event handlers instead of Effects. For more precise analytics, [intersection observers](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API) can help track which components are in the viewport and how long they remain visible.
+Para depurar os eventos de análise que você está enviando, você pode implantar seu aplicativo em um ambiente de staging (que roda em modo de produção) ou optar temporariamente por não participar do [Modo Estrito](/reference/react/StrictMode) e suas verificações de remontagem só em desenvolvimento. Você também pode enviar análises a partir dos manipuladores de eventos de mudança de rota em vez de Efeitos. Para análises mais precisas, [observadores de interseção](https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API) podem ajudar a rastrear quais componentes estão na viewport e quanto tempo permanecem visíveis.
-### Not an Effect: Initializing the application {/*not-an-effect-initializing-the-application*/}
+### Não um Efeito: Inicializando a aplicação {/*not-an-effect-initializing-the-application*/}
-Some logic should only run once when the application starts. You can put it outside your components:
+Alguma lógica deve ser executada apenas uma vez quando a aplicação inicia. Você pode colocá-la fora de seus componentes:
```js {2-3}
-if (typeof window !== 'undefined') { // Check if we're running in the browser.
+if (typeof window !== 'undefined') { // Verifique se estamos rodando no navegador.
checkAuthToken();
loadDataFromLocalStorage();
}
@@ -770,37 +769,37 @@ function App() {
}
```
-This guarantees that such logic only runs once after the browser loads the page.
+Isso garante que essa lógica só seja executada uma vez após o navegador carregar a página.
-### Not an Effect: Buying a product {/*not-an-effect-buying-a-product*/}
+### Não um Efeito: Comprando um produto {/*not-an-effect-buying-a-product*/}
-Sometimes, even if you write a cleanup function, there's no way to prevent user-visible consequences of running the Effect twice. For example, maybe your Effect sends a POST request like buying a product:
+Às vezes, mesmo que você escreva uma função de limpeza, não há como evitar as consequências visíveis para o usuário de executar o Efeito duas vezes. Por exemplo, talvez seu Efeito envie uma solicitação POST como comprar um produto:
```js {2-3}
useEffect(() => {
- // 🔴 Wrong: This Effect fires twice in development, exposing a problem in the code.
+ // 🔴 Errado: Este Efeito dispara duas vezes em desenvolvimento, expondo um problema no código.
fetch('/api/buy', { method: 'POST' });
}, []);
```
-You wouldn't want to buy the product twice. However, this is also why you shouldn't put this logic in an Effect. What if the user goes to another page and then presses Back? Your Effect would run again. You don't want to buy the product when the user *visits* a page; you want to buy it when the user *clicks* the Buy button.
+Você não gostaria de comprar o produto duas vezes. No entanto, isso é também porque você não deve colocar essa lógica em um Efeito. E se o usuário for para outra página e então pressionar Voltar? Seu Efeito executaria novamente. Você não quer comprar o produto quando o usuário *visita* uma página; você quer comprá-lo quando o usuário *clica* no botão Comprar.
-Buying is not caused by rendering; it's caused by a specific interaction. It should run only when the user presses the button. **Delete the Effect and move your `/api/buy` request into the Buy button event handler:**
+Comprar não é causado pela renderização; é causado por uma interação específica. Deve ser executado apenas quando o usuário pressionar o botão. **Exclua o Efeito e mova sua solicitação `/api/buy` para o manipulador de eventos do botão Buy:**
```js {2-3}
function handleClick() {
- // ✅ Buying is an event because it is caused by a particular interaction.
+ // ✅ Comprar é um evento porque é causado por uma interação específica.
fetch('/api/buy', { method: 'POST' });
}
```
-**This illustrates that if remounting breaks the logic of your application, this usually uncovers existing bugs.** From a user's perspective, visiting a page shouldn't be different from visiting it, clicking a link, then pressing Back to view the page again. React verifies that your components abide by this principle by remounting them once in development.
+**Isso ilustra que se a remontagem quebrar a lógica da sua aplicação, isso geralmente revela bugs existentes.** Do ponto de vista do usuário, visitar uma página não deve ser diferente de visitá-la, clicar em um link e depois pressionar Voltar para ver a página novamente. O React verifica que seus componentes respeitam esse princípio ao remontá-los uma vez em desenvolvimento.
-## Putting it all together {/*putting-it-all-together*/}
+## Juntando tudo {/*putting-it-all-together*/}
-This playground can help you "get a feel" for how Effects work in practice.
+Este playground pode ajudá-lo a "sentir" como os Efeitos funcionam na prática.
-This example uses [`setTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout) to schedule a console log with the input text to appear three seconds after the Effect runs. The cleanup function cancels the pending timeout. Start by pressing "Mount the component":
+Este exemplo usa [`setTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/setTimeout) para programar um registro de console com o texto de entrada para aparecer três segundos após o Efeito ser executado. A função de limpeza cancela o timeout pendente. Comece pressionando "Montar o componente":
@@ -815,11 +814,11 @@ function Playground() {
console.log('⏰ ' + text);
}
- console.log('🔵 Schedule "' + text + '" log');
+ console.log('🔵 Agendar log "' + text + '"');
const timeoutId = setTimeout(onTimeout, 3000);
return () => {
- console.log('🟡 Cancel "' + text + '" log');
+ console.log('🟡 Cancelar log "' + text + '"');
clearTimeout(timeoutId);
};
}, [text]);
@@ -827,7 +826,7 @@ function Playground() {
return (
<>
- What to log:{' '}
+ O que logar:{' '}
setText(e.target.value)}
@@ -843,7 +842,7 @@ export default function App() {
return (
<>
setShow(!show)}>
- {show ? 'Unmount' : 'Mount'} the component
+ {show ? 'Desmontar' : 'Montar'} o componente
{show && }
{show && }
@@ -854,21 +853,21 @@ export default function App() {
-You will see three logs at first: `Schedule "a" log`, `Cancel "a" log`, and `Schedule "a" log` again. Three second later there will also be a log saying `a`. As you learned earlier, the extra schedule/cancel pair is because React remounts the component once in development to verify that you've implemented cleanup well.
+Você verá três logs inicialmente: `Agendar "a" log`, `Cancelar "a" log`, e `Agendar "a" log` novamente. Três segundos depois, haverá também um log dizendo `a`. Como você aprendeu anteriormente, o par extra de agendar/cancelar é porque o React remonta o componente uma vez em desenvolvimento para verificar se você implementou a limpeza bem.
-Now edit the input to say `abc`. If you do it fast enough, you'll see `Schedule "ab" log` immediately followed by `Cancel "ab" log` and `Schedule "abc" log`. **React always cleans up the previous render's Effect before the next render's Effect.** This is why even if you type into the input fast, there is at most one timeout scheduled at a time. Edit the input a few times and watch the console to get a feel for how Effects get cleaned up.
+Agora edite a entrada para dizer `abc`. Se você fizer isso rapidamente, verá `Agendar "ab" log` imediatamente seguido por `Cancelar "ab" log` e `Agendar "abc" log`. **O React sempre limpa o Efeito da renderização anterior antes do Efeito da próxima renderização.** É por isso que, mesmo que você digite rapidamente na entrada, há no máximo um timeout agendado de cada vez. Edite a entrada algumas vezes e observe o console para sentir como os Efeitos são limpos.
-Type something into the input and then immediately press "Unmount the component". Notice how unmounting cleans up the last render's Effect. Here, it clears the last timeout before it has a chance to fire.
+Digite algo na entrada e então pressione imediatamente "Desmontar o componente". Note como desmontar limpa o Efeito da última renderização. Aqui, ele limpa o último timeout antes que tenha chance de disparar.
-Finally, edit the component above and comment out the cleanup function so that the timeouts don't get cancelled. Try typing `abcde` fast. What do you expect to happen in three seconds? Will `console.log(text)` inside the timeout print the *latest* `text` and produce five `abcde` logs? Give it a try to check your intuition!
+Finalmente, edite o componente acima e comente a função de limpeza para que os timeouts não sejam cancelados. Tente digitar `abcde` rapidamente. O que você espera que aconteça em três segundos? O registro `console.log(text)` dentro do timeout imprimirá o *texto mais recente* e produzirá cinco logs de `abcde`? Dê uma tentativa para verificar sua intuição!
-Three seconds later, you should see a sequence of logs (`a`, `ab`, `abc`, `abcd`, and `abcde`) rather than five `abcde` logs. **Each Effect "captures" the `text` value from its corresponding render.** It doesn't matter that the `text` state changed: an Effect from the render with `text = 'ab'` will always see `'ab'`. In other words, Effects from each render are isolated from each other. If you're curious how this works, you can read about [closures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures).
+Três segundos depois, você deverá ver uma sequência de logs (`a`, `ab`, `abc`, `abcd`, e `abcde`) em vez de cinco logs `abcde`. **Cada Efeito "captura" o valor de `text` de sua renderização correspondente.** Não importa que o estado `text` tenha mudado: um Efeito da renderização com `text = 'ab'` sempre verá `'ab'`. Em outras palavras, os Efeitos de cada renderização são isolados uns dos outros. Se você está curioso sobre como isso funciona, pode ler sobre [closures](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures).
-#### Each render has its own Effects {/*each-render-has-its-own-effects*/}
+#### Cada renderização tem seus próprios Efeitos {/*each-render-has-its-own-effects*/}
-You can think of `useEffect` as "attaching" a piece of behavior to the render output. Consider this Effect:
+Você pode pensar em `useEffect` como "anexar" um pedaço de comportamento à saída de renderização. Considere este Efeito:
```js
export default function ChatRoom({ roomId }) {
@@ -878,123 +877,123 @@ export default function ChatRoom({ roomId }) {
return () => connection.disconnect();
}, [roomId]);
- return Welcome to {roomId}! ;
+ return Bem-vindo a {roomId}! ;
}
```
-Let's see what exactly happens as the user navigates around the app.
+Vamos ver o que exatamente acontece à medida que o usuário navega pelo aplicativo.
-#### Initial render {/*initial-render*/}
+#### Renderização inicial {/*initial-render*/}
-The user visits ` `. Let's [mentally substitute](/learn/state-as-a-snapshot#rendering-takes-a-snapshot-in-time) `roomId` with `'general'`:
+O usuário visita ` `. Vamos [substituir mentalmente](/learn/state-as-a-snapshot#rendering-takes-a-snapshot-in-time) `roomId` por `'geral'`:
```js
- // JSX for the first render (roomId = "general")
- return Welcome to general! ;
+ // JSX para a primeira renderização (roomId = "geral")
+ return Bem-vindo a geral! ;
```
-**The Effect is *also* a part of the rendering output.** The first render's Effect becomes:
+**O Efeito é *também* parte da saída de renderização.** O Efeito da primeira renderização torna-se:
```js
- // Effect for the first render (roomId = "general")
+ // Efeito para a primeira renderização (roomId = "geral")
() => {
- const connection = createConnection('general');
+ const connection = createConnection('geral');
connection.connect();
return () => connection.disconnect();
},
- // Dependencies for the first render (roomId = "general")
- ['general']
+ // Dependências para a primeira renderização (roomId = "geral")
+ ['geral']
```
-React runs this Effect, which connects to the `'general'` chat room.
+O React executa esse Efeito, que conecta à sala de chat `'geral'`.
-#### Re-render with same dependencies {/*re-render-with-same-dependencies*/}
+#### Re-renderização com as mesmas dependências {/*re-render-with-same-dependencies*/}
-Let's say ` ` re-renders. The JSX output is the same:
+Suponha que ` ` re-renderize. A saída JSX é a mesma:
```js
- // JSX for the second render (roomId = "general")
- return Welcome to general! ;
+ // JSX para a segunda renderização (roomId = "geral")
+ return Bem-vindo a geral! ;
```
-React sees that the rendering output has not changed, so it doesn't update the DOM.
+O React vê que a saída de renderização não mudou, então ele não atualiza o DOM.
-The Effect from the second render looks like this:
+O Efeito da segunda renderização parece assim:
```js
- // Effect for the second render (roomId = "general")
+ // Efeito para a segunda renderização (roomId = "geral")
() => {
- const connection = createConnection('general');
+ const connection = createConnection('geral');
connection.connect();
return () => connection.disconnect();
},
- // Dependencies for the second render (roomId = "general")
- ['general']
+ // Dependências para a segunda renderização (roomId = "geral")
+ ['geral']
```
-React compares `['general']` from the second render with `['general']` from the first render. **Because all dependencies are the same, React *ignores* the Effect from the second render.** It never gets called.
+O React compara `['geral']` da segunda renderização com `['geral']` da primeira renderização. **Como todas as dependências são as mesmas, o React *ignora* o Efeito da segunda renderização.** Ele nunca é chamado.
-#### Re-render with different dependencies {/*re-render-with-different-dependencies*/}
+#### Re-renderização com dependências diferentes {/*re-render-with-different-dependencies*/}
-Then, the user visits ` `. This time, the component returns different JSX:
+Então, o usuário visita ` `. Desta vez, o componente retorna JSX diferente:
```js
- // JSX for the third render (roomId = "travel")
- return Welcome to travel! ;
+ // JSX para a terceira renderização (roomId = "viagem")
+ return Bem-vindo a viagem! ;
```
-React updates the DOM to change `"Welcome to general"` into `"Welcome to travel"`.
+O React atualiza o DOM para mudar `"Bem-vindo a geral"` para `"Bem-vindo a viagem"`.
-The Effect from the third render looks like this:
+O Efeito da terceira renderização parece assim:
```js
- // Effect for the third render (roomId = "travel")
+ // Efeito para a terceira renderização (roomId = "viagem")
() => {
- const connection = createConnection('travel');
+ const connection = createConnection('viagem');
connection.connect();
return () => connection.disconnect();
},
- // Dependencies for the third render (roomId = "travel")
- ['travel']
+ // Dependências para a terceira renderização (roomId = "viagem")
+ ['viagem']
```
-React compares `['travel']` from the third render with `['general']` from the second render. One dependency is different: `Object.is('travel', 'general')` is `false`. The Effect can't be skipped.
+O React compara `['viagem']` da terceira renderização com `['geral']` da segunda renderização. Uma dependência é diferente: `Object.is('viagem', 'geral')` é `false`. O Efeito não pode ser pulado.
-**Before React can apply the Effect from the third render, it needs to clean up the last Effect that _did_ run.** The second render's Effect was skipped, so React needs to clean up the first render's Effect. If you scroll up to the first render, you'll see that its cleanup calls `disconnect()` on the connection that was created with `createConnection('general')`. This disconnects the app from the `'general'` chat room.
+**Antes que o React possa aplicar o Efeito da terceira renderização, ele precisa limpar o último Efeito que _foi_ executado.** O Efeito da segunda renderização foi pulado, então o React precisa limpar o Efeito da primeira renderização. Se você rolar para cima até a primeira renderização, verá que sua limpeza chama `disconnect()` na conexão que foi criada com `createConnection('geral')`. Isso desconecta o aplicativo da sala de chat `'geral'`.
-After that, React runs the third render's Effect. It connects to the `'travel'` chat room.
+Após isso, o React executa o Efeito da terceira renderização. Conecta-se à sala de chat `'viagem'`.
-#### Unmount {/*unmount*/}
+#### Desmontar {/*unmount*/}
-Finally, let's say the user navigates away, and the `ChatRoom` component unmounts. React runs the last Effect's cleanup function. The last Effect was from the third render. The third render's cleanup destroys the `createConnection('travel')` connection. So the app disconnects from the `'travel'` room.
+Finalmente, suponha que o usuário navega para longe, e o componente `ChatRoom` se desmonta. O React executa a função de limpeza do último Efeito. O último Efeito foi da terceira renderização. A função de limpeza da terceira renderização destrói a conexão `createConnection('viagem')`. Portanto, o aplicativo desconecta da sala `'viagem'`.
-#### Development-only behaviors {/*development-only-behaviors*/}
+#### Comportamentos apenas de desenvolvimento {/*development-only-behaviors*/}
-When [Strict Mode](/reference/react/StrictMode) is on, React remounts every component once after mount (state and DOM are preserved). This [helps you find Effects that need cleanup](#step-3-add-cleanup-if-needed) and exposes bugs like race conditions early. Additionally, React will remount the Effects whenever you save a file in development. Both of these behaviors are development-only.
+Quando o [Modo Estrito](/reference/react/StrictMode) está ativado, o React remonta cada componente uma vez após a montagem (o estado e o DOM são preservados). Isso [ajuda você a encontrar Efeitos que precisam de limpeza](#step-3-add-cleanup-if-needed) e expõe erros como condições de corrida precocemente. Além disso, o React remonta os Efeitos sempre que você salva um arquivo em desenvolvimento. Ambos esses comportamentos são apenas para desenvolvimento.
-- Unlike events, Effects are caused by rendering itself rather than a particular interaction.
-- Effects let you synchronize a component with some external system (third-party API, network, etc).
-- By default, Effects run after every render (including the initial one).
-- React will skip the Effect if all of its dependencies have the same values as during the last render.
-- You can't "choose" your dependencies. They are determined by the code inside the Effect.
-- Empty dependency array (`[]`) corresponds to the component "mounting", i.e. being added to the screen.
-- In Strict Mode, React mounts components twice (in development only!) to stress-test your Effects.
-- If your Effect breaks because of remounting, you need to implement a cleanup function.
-- React will call your cleanup function before the Effect runs next time, and during the unmount.
+- Ao contrário dos eventos, os Efeitos são causados pela própria renderização em vez de uma interação particular.
+- Efeitos permitem que você sincronize um componente com algum sistema externo (API de terceiros, rede, etc).
+- Por padrão, os Efeitos são executados após cada renderização (incluindo a inicial).
+- O React pulará o Efeito se todas as suas dependências tiverem os mesmos valores que durante a última renderização.
+- Você não pode "escolher" suas dependências. Elas são determinadas pelo código dentro do Efeito.
+- Um array de dependências vazio (`[]`) corresponde à "montagem" do componente, ou seja, sendo adicionado à tela.
+- No Modo Estrito, o React monta os componentes duas vezes (apenas em desenvolvimento!) para testar seus Efeitos.
+- Se o seu Efeito quebrar devido à remontagem, você precisa implementar uma função de limpeza.
+- O React chamará sua função de limpeza antes que o Efeito seja executado na próxima vez e durante a desmontagem.
-#### Focus a field on mount {/*focus-a-field-on-mount*/}
+#### Focar um campo na montagem {/*focus-a-field-on-mount*/}
-In this example, the form renders a ` ` component.
+Neste exemplo, o formulário renderiza um componente ` `.
-Use the input's [`focus()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) method to make `MyInput` automatically focus when it appears on the screen. There is already a commented out implementation, but it doesn't quite work. Figure out why it doesn't work, and fix it. (If you're familiar with the `autoFocus` attribute, pretend that it does not exist: we are reimplementing the same functionality from scratch.)
+Use o método [`focus()`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus) do input para fazer o `MyInput` automaticamente receber foco quando aparece na tela. Já há uma implementação comentada, mas ela não funciona exatamente. Descubra por que não funciona e conserte.
@@ -1004,7 +1003,7 @@ import { useEffect, useRef } from 'react';
export default function MyInput({ value, onChange }) {
const ref = useRef(null);
- // TODO: This doesn't quite work. Fix it.
+ // TODO: Isso não funciona exatamente. Conserte-o.
// ref.current.focus()
return (
@@ -1027,13 +1026,13 @@ export default function Form() {
const [upper, setUpper] = useState(false);
return (
<>
- setShow(s => !s)}>{show ? 'Hide' : 'Show'} form
+ setShow(s => !s)}>{show ? 'Esconder' : 'Mostrar'} formulário
{show && (
<>
- Enter your name:
+ Digite seu nome:
setName(e.target.value)}
@@ -1045,9 +1044,9 @@ export default function Form() {
checked={upper}
onChange={e => setUpper(e.target.checked)}
/>
- Make it uppercase
+ Torná-lo maiúsculo
- Hello, {upper ? name.toUpperCase() : name}
+ Olá, {upper ? name.toUpperCase() : name}
>
)}
>
@@ -1070,15 +1069,15 @@ body {
-To verify that your solution works, press "Show form" and verify that the input receives focus (becomes highlighted and the cursor is placed inside). Press "Hide form" and "Show form" again. Verify the input is highlighted again.
+Para verificar se sua solução funciona, pressione "Mostrar formulário" e verifique se o input recebe foco (fica destacado e o cursor é colocado dentro). Pressione "Esconder formulário" e "Mostrar formulário" novamente. Verifique se o input é destacado novamente.
-`MyInput` should only focus _on mount_ rather than after every render. To verify that the behavior is right, press "Show form" and then repeatedly press the "Make it uppercase" checkbox. Clicking the checkbox should _not_ focus the input above it.
+O `MyInput` deve apenas focar _na montagem_ em vez de após cada renderização. Para verificar se o comportamento está correto, pressione "Mostrar formulário" e em seguida pressione repetidamente a caixa de seleção "Torná-lo maiúsculo". Clicar na caixa de seleção não deve _focar_ o input acima.
-Calling `ref.current.focus()` during render is wrong because it is a *side effect*. Side effects should either be placed inside an event handler or be declared with `useEffect`. In this case, the side effect is _caused_ by the component appearing rather than by any specific interaction, so it makes sense to put it in an Effect.
+Chamar `ref.current.focus()` durante a renderização está errado pois é um *efeito colateral*. Efeitos colaterais devem ser colocados dentro de um manipulador de eventos ou serem declarados com `useEffect`. Neste caso, o efeito colateral é _causado_ pelo componente aparecendo em vez de por qualquer interação específica, portanto faz sentido colocá-lo em um Efeito.
-To fix the mistake, wrap the `ref.current.focus()` call into an Effect declaration. Then, to ensure that this Effect runs only on mount rather than after every render, add the empty `[]` dependencies to it.
+Para corrigir o erro, envolva a chamada `ref.current.focus()` em uma declaração de Efeito. Em seguida, para garantir que esse Efeito seja executado apenas na montagem em vez de após cada renderização, adicione o array vazio `[]` a ele.
@@ -1112,13 +1111,13 @@ export default function Form() {
const [upper, setUpper] = useState(false);
return (
<>
- setShow(s => !s)}>{show ? 'Hide' : 'Show'} form
+ setShow(s => !s)}>{show ? 'Esconder' : 'Mostrar'} formulário
{show && (
<>
- Enter your name:
+ Digite seu nome:
setName(e.target.value)}
@@ -1130,9 +1129,9 @@ export default function Form() {
checked={upper}
onChange={e => setUpper(e.target.checked)}
/>
- Make it uppercase
+ Torná-lo maiúsculo
- Hello, {upper ? name.toUpperCase() : name}
+ Olá, {upper ? name.toUpperCase() : name}
>
)}
>
@@ -1156,13 +1155,13 @@ body {
-#### Focus a field conditionally {/*focus-a-field-conditionally*/}
+#### Focar um campo condicionalmente {/*focus-a-field-conditionally*/}
-This form renders two ` ` components.
+Este formulário renderiza dois componentes ` `.
-Press "Show form" and notice that the second field automatically gets focused. This is because both of the ` ` components try to focus the field inside. When you call `focus()` for two input fields in a row, the last one always "wins".
+Pressione "Mostrar formulário" e note que o segundo campo automaticamente recebe foco. Isso ocorre porque ambos os componentes ` ` tentam focar o campo interno. Quando você chama `focus()` para dois campos de entrada em sequência, o último sempre "vence".
-Let's say you want to focus the first field. The first `MyInput` component now receives a boolean `shouldFocus` prop set to `true`. Change the logic so that `focus()` is only called if the `shouldFocus` prop received by `MyInput` is `true`.
+Vamos supor que você deseja focar o primeiro campo. O primeiro componente `MyInput` agora recebe uma prop booleana `shouldFocus` definida como `true`. Altere a lógica para que `focus()` seja chamado apenas se a prop `shouldFocus` recebida pelo `MyInput` for `true`.
@@ -1172,7 +1171,7 @@ import { useEffect, useRef } from 'react';
export default function MyInput({ shouldFocus, value, onChange }) {
const ref = useRef(null);
- // TODO: call focus() only if shouldFocus is true.
+ // TODO: chamar focus() apenas se shouldFocus for verdadeiro.
useEffect(() => {
ref.current.focus();
}, []);
@@ -1199,13 +1198,13 @@ export default function Form() {
const name = firstName + ' ' + lastName;
return (
<>
- setShow(s => !s)}>{show ? 'Hide' : 'Show'} form
+ setShow(s => !s)}>{show ? 'Esconder' : 'Mostrar'} formulário
{show && (
<>
- Enter your first name:
+ Digite seu primeiro nome:
setFirstName(e.target.value)}
@@ -1213,14 +1212,14 @@ export default function Form() {
/>
- Enter your last name:
+ Digite seu sobrenome:
setLastName(e.target.value)}
shouldFocus={false}
/>
- Hello, {upper ? name.toUpperCase() : name}
+ Olá, {upper ? name.toUpperCase() : name}
>
)}
>
@@ -1242,17 +1241,17 @@ body {
-To verify your solution, press "Show form" and "Hide form" repeatedly. When the form appears, only the *first* input should get focused. This is because the parent component renders the first input with `shouldFocus={true}` and the second input with `shouldFocus={false}`. Also check that both inputs still work and you can type into both of them.
+Para verificar sua solução, pressione "Mostrar formulário" e "Esconder formulário" repetidamente. Quando o formulário aparecer, apenas o *primeiro* input deve receber foco. Isso ocorre porque o componente pai renderiza o primeiro input com `shouldFocus={true}` e o segundo input com `shouldFocus={false}`. Também verifique se ambos os inputs ainda funcionam e você pode digitar em ambos.
-You can't declare an Effect conditionally, but your Effect can include conditional logic.
+Você não pode declarar um Efeito condicionalmente, mas seu Efeito pode incluir lógica condicional.
-Put the conditional logic inside the Effect. You will need to specify `shouldFocus` as a dependency because you are using it inside the Effect. (This means that if some input's `shouldFocus` changes from `false` to `true`, it will focus after mount.)
+Coloque a lógica condicional dentro do Efeito. Você precisará especificar `shouldFocus` como uma dependência porque está utilizando-a dentro do Efeito. (Isso significa que se a prop de algum input mudar de `false` para `true`, ela se focará após a montagem.)
@@ -1290,13 +1289,13 @@ export default function Form() {
const name = firstName + ' ' + lastName;
return (
<>
- setShow(s => !s)}>{show ? 'Hide' : 'Show'} form
+ setShow(s => !s)}>{show ? 'Esconder' : 'Mostrar'} formulário
{show && (
<>
- Enter your first name:
+ Digite seu primeiro nome:
setFirstName(e.target.value)}
@@ -1304,14 +1303,14 @@ export default function Form() {
/>
- Enter your last name:
+ Digite seu sobrenome:
setLastName(e.target.value)}
shouldFocus={false}
/>
- Hello, {upper ? name.toUpperCase() : name}
+ Olá, {upper ? name.toUpperCase() : name}
>
)}
>
@@ -1335,15 +1334,15 @@ body {
-#### Fix an interval that fires twice {/*fix-an-interval-that-fires-twice*/}
+#### Corrigir um intervalo que dispara duas vezes {/*fix-an-interval-that-fires-twice*/}
-This `Counter` component displays a counter that should increment every second. On mount, it calls [`setInterval`.](https://developer.mozilla.org/en-US/docs/Web/API/setInterval) This causes `onTick` to run every second. The `onTick` function increments the counter.
+Este componente `Counter` exibe um contador que deve incrementar a cada segundo. Na montagem, ele chama [`setInterval`](https://developer.mozilla.org/en-US/docs/Web/API/setInterval). Isso faz com que `onTick` seja executado a cada segundo. A função `onTick` incrementa o contador.
-However, instead of incrementing once per second, it increments twice. Why is that? Find the cause of the bug and fix it.
+No entanto, em vez de incrementar uma vez por segundo, ele incrementa duas vezes. Qual é a causa do bug? Corrija-o.
-Keep in mind that `setInterval` returns an interval ID, which you can pass to [`clearInterval`](https://developer.mozilla.org/en-US/docs/Web/API/clearInterval) to stop the interval.
+Tenha em mente que `setInterval` retorna um ID de intervalo, que você pode passar para [`clearInterval`](https://developer.mozilla.org/en-US/docs/Web/API/clearInterval) para parar o intervalo.
@@ -1375,7 +1374,7 @@ export default function Form() {
const [show, setShow] = useState(false);
return (
<>
- setShow(s => !s)}>{show ? 'Hide' : 'Show'} counter
+ setShow(s => !s)}>{show ? 'Esconder' : 'Mostrar'} contador
{show && }
@@ -1400,11 +1399,11 @@ body {
-When [Strict Mode](/reference/react/StrictMode) is on (like in the sandboxes on this site), React remounts each component once in development. This causes the interval to be set up twice, and this is why each second the counter increments twice.
+Quando o [Modo Estrito](/reference/react/StrictMode) está ativado (como nas caixas de areia neste site), o React remonta cada componente uma vez em desenvolvimento. Isso faz com que o intervalo seja configurado duas vezes, e é por isso que o contador incrementa duas vezes a cada segundo.
-However, React's behavior is not the *cause* of the bug: the bug already exists in the code. React's behavior makes the bug more noticeable. The real cause is that this Effect starts a process but doesn't provide a way to clean it up.
+No entanto, o comportamento do React não é a *causa* do bug: o bug já existe no código. O comportamento do React torna o bug mais perceptível. A verdadeira causa é que este Efeito inicia um processo, mas não fornece uma maneira de limpá-lo.
-To fix this code, save the interval ID returned by `setInterval`, and implement a cleanup function with [`clearInterval`](https://developer.mozilla.org/en-US/docs/Web/API/clearInterval):
+Para corrigir este código, salve o ID de intervalo retornado por `setInterval` e implemente uma função de limpeza com [`clearInterval`](https://developer.mozilla.org/en-US/docs/Web/API/clearInterval):
@@ -1435,7 +1434,7 @@ export default function App() {
const [show, setShow] = useState(false);
return (
<>
- setShow(s => !s)}>{show ? 'Hide' : 'Show'} counter
+ setShow(s => !s)}>{show ? 'Esconder' : 'Mostrar'} contador
{show && }
@@ -1458,151 +1457,4 @@ body {
-In development, React will still remount your component once to verify that you've implemented cleanup well. So there will be a `setInterval` call, immediately followed by `clearInterval`, and `setInterval` again. In production, there will be only one `setInterval` call. The user-visible behavior in both cases is the same: the counter increments once per second.
-
-
-
-#### Fix fetching inside an Effect {/*fix-fetching-inside-an-effect*/}
-
-This component shows the biography for the selected person. It loads the biography by calling an asynchronous function `fetchBio(person)` on mount and whenever `person` changes. That asynchronous function returns a [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) which eventually resolves to a string. When fetching is done, it calls `setBio` to display that string under the select box.
-
-
-
-```js src/App.js
-import { useState, useEffect } from 'react';
-import { fetchBio } from './api.js';
-
-export default function Page() {
- const [person, setPerson] = useState('Alice');
- const [bio, setBio] = useState(null);
-
- useEffect(() => {
- setBio(null);
- fetchBio(person).then(result => {
- setBio(result);
- });
- }, [person]);
-
- return (
- <>
- {
- setPerson(e.target.value);
- }}>
- Alice
- Bob
- Taylor
-
-
- {bio ?? 'Loading...'}
- >
- );
-}
-```
-
-```js src/api.js hidden
-export async function fetchBio(person) {
- const delay = person === 'Bob' ? 2000 : 200;
- return new Promise(resolve => {
- setTimeout(() => {
- resolve('This is ' + person + '’s bio.');
- }, delay);
- })
-}
-
-```
-
-
-
-
-There is a bug in this code. Start by selecting "Alice". Then select "Bob" and then immediately after that select "Taylor". If you do this fast enough, you will notice that bug: Taylor is selected, but the paragraph below says "This is Bob's bio."
-
-Why does this happen? Fix the bug inside this Effect.
-
-
-
-If an Effect fetches something asynchronously, it usually needs cleanup.
-
-
-
-
-
-To trigger the bug, things need to happen in this order:
-
-- Selecting `'Bob'` triggers `fetchBio('Bob')`
-- Selecting `'Taylor'` triggers `fetchBio('Taylor')`
-- **Fetching `'Taylor'` completes *before* fetching `'Bob'`**
-- The Effect from the `'Taylor'` render calls `setBio('This is Taylor’s bio')`
-- Fetching `'Bob'` completes
-- The Effect from the `'Bob'` render calls `setBio('This is Bob’s bio')`
-
-This is why you see Bob's bio even though Taylor is selected. Bugs like this are called [race conditions](https://en.wikipedia.org/wiki/Race_condition) because two asynchronous operations are "racing" with each other, and they might arrive in an unexpected order.
-
-To fix this race condition, add a cleanup function:
-
-
-
-```js src/App.js
-import { useState, useEffect } from 'react';
-import { fetchBio } from './api.js';
-
-export default function Page() {
- const [person, setPerson] = useState('Alice');
- const [bio, setBio] = useState(null);
- useEffect(() => {
- let ignore = false;
- setBio(null);
- fetchBio(person).then(result => {
- if (!ignore) {
- setBio(result);
- }
- });
- return () => {
- ignore = true;
- }
- }, [person]);
-
- return (
- <>
- {
- setPerson(e.target.value);
- }}>
- Alice
- Bob
- Taylor
-
-
- {bio ?? 'Loading...'}
- >
- );
-}
-```
-
-```js src/api.js hidden
-export async function fetchBio(person) {
- const delay = person === 'Bob' ? 2000 : 200;
- return new Promise(resolve => {
- setTimeout(() => {
- resolve('This is ' + person + '’s bio.');
- }, delay);
- })
-}
-
-```
-
-
-
-Each render's Effect has its own `ignore` variable. Initially, the `ignore` variable is set to `false`. However, if an Effect gets cleaned up (such as when you select a different person), its `ignore` variable becomes `true`. So now it doesn't matter in which order the requests complete. Only the last person's Effect will have `ignore` set to `false`, so it will call `setBio(result)`. Past Effects have been cleaned up, so the `if (!ignore)` check will prevent them from calling `setBio`:
-
-- Selecting `'Bob'` triggers `fetchBio('Bob')`
-- Selecting `'Taylor'` triggers `fetchBio('Taylor')` **and cleans up the previous (Bob's) Effect**
-- Fetching `'Taylor'` completes *before* fetching `'Bob'`
-- The Effect from the `'Taylor'` render calls `setBio('This is Taylor’s bio')`
-- Fetching `'Bob'` completes
-- The Effect from the `'Bob'` render **does not do anything because its `ignore` flag was set to `true`**
-
-In addition to ignoring the result of an outdated API call, you can also use [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) to cancel the requests that are no longer needed. However, by itself this is not enough to protect against race conditions. More asynchronous steps could be chained after the fetch, so using an explicit flag like `ignore` is the most reliable way to fix this type of problems.
-
-
-
-
-
+No desenvolvimento, o React ainda remonta seu componente uma vez para verificar se você implementou a limpeza corretamente. Portanto, haverá uma chamada de `setInterval`, imediatamente seguida por `clearInterval`, e `setInterval` novamente. Na
\ No newline at end of file