diff --git a/src/content/learn/state-a-components-memory.md b/src/content/learn/state-a-components-memory.md
index 10499a003..8d5c32312 100644
--- a/src/content/learn/state-a-components-memory.md
+++ b/src/content/learn/state-a-components-memory.md
@@ -1,25 +1,25 @@
---
-title: "State: A Component's Memory"
+title: "State: A Memória de um Componente"
---
-Components often need to change what's on the screen as a result of an interaction. Typing into the form should update the input field, clicking "next" on an image carousel should change which image is displayed, clicking "buy" should put a product in the shopping cart. Components need to "remember" things: the current input value, the current image, the shopping cart. In React, this kind of component-specific memory is called *state*.
+Componentes comumente precisam mudar o que está na tela como resultado de uma interação. Digitar em um formulário deve atualizar o campo de entrada, clicar em "próximo" em um carrossel de imagens deve mudar qual imagem é exibida, clicar em "comprar" deve colocar um produto no carrinho. Componentes precisam "lembrar" de coisas: o valor de entrada atual, a imagem atual, o carrinho de compras. Em React, esse tipo de memória componente-específica é chamado de *state*.
-* How to add a state variable with the [`useState`](/reference/react/useState) Hook
-* What pair of values the `useState` Hook returns
-* How to add more than one state variable
-* Why state is called local
+* Como adicionar uma variável de state com o Hook [`useState`](/reference/react/useState)
+* Qual o par de valores retornado pelo Hook `useState`
+* Como adicionar mais de uma variável de state
+* Por que o state é chamado de local
-## When a regular variable isn’t enough {/*when-a-regular-variable-isnt-enough*/}
+## Quando uma variável comum não é o suficiente {/*when-a-regular-variable-isnt-enough*/}
-Here's a component that renders a sculpture image. Clicking the "Next" button should show the next sculpture by changing the `index` to `1`, then `2`, and so on. However, this **won't work** (you can try it!):
+Aqui está um componente que renderiza a imagem de uma escultura. Ao clicar no botão "Next" ele deveria mostrar a próxima escultura mudando o `index` para `1`, então `2`, e assim por diante. Entretanto, isso **não funcionará** (você pode tentar!):
@@ -151,46 +151,46 @@ button {
-The `handleClick` event handler is updating a local variable, `index`. But two things prevent that change from being visible:
+O manipulador de eventos `handleClick` está atualizando a variável local, `index`. Mas duas coisas previnem essa mudança de ser visível:
-1. **Local variables don't persist between renders.** When React renders this component a second time, it renders it from scratch—it doesn't consider any changes to the local variables.
-2. **Changes to local variables won't trigger renders.** React doesn't realize it needs to render the component again with the new data.
+1. **Variáveis locais não persistem entre renderizações.** Quando o React renderiza esse componente uma segunda vez, ele o faz do princípio--sem considerar quaisquer mudanças às variáveis locais.
+2. **Mudanças às variáveis locais não acionam renderizações.** O React não percebe que precisa renderizar o componente novamente com os novos dados.
-To update a component with new data, two things need to happen:
+Para atualizar um componente com novos dados, duas coisas precisam acontecer:
-1. **Retain** the data between renders.
-2. **Trigger** React to render the component with new data (re-rendering).
+1. **Reter** os dados entre renderizações.
+2. **Acionar** o React para renderizar o componente com os novos dados (rerrenderização).
-The [`useState`](/reference/react/useState) Hook provides those two things:
+O Hook [`useState`](/reference/react/useState) provê essas duas coisas:
-1. A **state variable** to retain the data between renders.
-2. A **state setter function** to update the variable and trigger React to render the component again.
+1. Uma **Variável de state** para reter os dados entre renderizações.
+2. Uma **função de definição de state** para atualizar a variável e acionar o React para renderizar o componente novamente.
-## Adding a state variable {/*adding-a-state-variable*/}
+## Adicionando uma variável de estado {/*adding-a-state-variable*/}
-To add a state variable, import `useState` from React at the top of the file:
+Para adicionar uma variável de estado, importe `useState` do React no topo do arquivo:
```js
import { useState } from 'react';
```
-Then, replace this line:
+Então, substitua essa linha:
```js
let index = 0;
```
-with
+com
```js
const [index, setIndex] = useState(0);
```
-`index` is a state variable and `setIndex` is the setter function.
+`index` é uma variável de estado e `setIndex` é a função de definição.
-> The `[` and `]` syntax here is called [array destructuring](https://javascript.info/destructuring-assignment) and it lets you read values from an array. The array returned by `useState` always has exactly two items.
+> A sintaxe `[` e `]` aqui é chamada de [desestruturação de array](https://javascript.info/destructuring-assignment) e ela permite que você leia valores de um array. O array retornado pelo `useState` sempre possui exatamente dois itens.
-This is how they work together in `handleClick`:
+Essa é a maneira como eles trabalham juntos em `handleClick`:
```js
function handleClick() {
@@ -198,7 +198,7 @@ function handleClick() {
}
```
-Now clicking the "Next" button switches the current sculpture:
+Agora clicar no botão "Next" muda a escultura atual:
@@ -331,57 +331,57 @@ button {
-### Meet your first Hook {/*meet-your-first-hook*/}
+### Conheça seu primero Hook {/*meet-your-first-hook*/}
-In React, `useState`, as well as any other function starting with "`use`", is called a Hook.
+No React, `useState`, assim como qualquer outra função iniciada com "`use`", é denominada de Hook.
-*Hooks* are special functions that are only available while React is [rendering](/learn/render-and-commit#step-1-trigger-a-render) (which we'll get into in more detail on the next page). They let you "hook into" different React features.
+*Hooks* são funções especiais que estão disponíveis somente enquanto o React está [renderizando](/learn/render-and-commit#step-1-trigger-a-render) (as quais nós entraremos em mais detalhes na próxima página). Eles permitem que você "se conecte" a diferentes recursos do React.
-State is just one of those features, but you will meet the other Hooks later.
+State é só um destes recursos, mas você irá conhecer os outros Hooks mais tarde.
-**Hooks—functions starting with `use`—can only be called at the top level of your components or [your own Hooks.](/learn/reusing-logic-with-custom-hooks)** You can't call Hooks inside conditions, loops, or other nested functions. Hooks are functions, but it's helpful to think of them as unconditional declarations about your component's needs. You "use" React features at the top of your component similar to how you "import" modules at the top of your file.
+**Hooks--funções iniciadas com `use`--só podem ser chamadas no nível superior dos seus componentes ou em [seus próprios Hooks.](/learn/reusing-logic-with-custom-hooks)** Você não pode chamar Hooks dentro de condições, loops, ou outras funções aninhadas. Hooks são funções, mas é útil pensar neles como declarações incondicionais sobre as necessidades do seu componente. Você "usa" recursos do React no topo de seu componente similarmente a como você "importa" módulos no topo de seu arquivo.
-### Anatomy of `useState` {/*anatomy-of-usestate*/}
+### Anatomia do `useState` {/*anatomy-of-usestate*/}
-When you call [`useState`](/reference/react/useState), you are telling React that you want this component to remember something:
+Ao chamar [`useState`](/reference/react/useState), você está dizendo ao React que você quer que esse componente lembre-se de algo:
```js
const [index, setIndex] = useState(0);
```
-In this case, you want React to remember `index`.
+Nesse caso, você quer que o React lembre-se de `index`.
-The convention is to name this pair like `const [something, setSomething]`. You could name it anything you like, but conventions make things easier to understand across projects.
+A convenção é nomear esse par como `const [algo, setAlgo]`. Você poderia nomeá-lo de qualquer outra coisa, mas convenções tornam as coisas mais fáceis de se entender entre projetos.
-The only argument to `useState` is the **initial value** of your state variable. In this example, the `index`'s initial value is set to `0` with `useState(0)`.
+O único argumento para o `useState` é o **valor inicial** da sua variável de state. Nesse exemplo, o valor inicial de `index` é definido como `0` com `useState(0)`.
-Every time your component renders, `useState` gives you an array containing two values:
+Toda vez que seu componente é renderizado, `useState` lhe dá um array contendo dois valores:
-1. The **state variable** (`index`) with the value you stored.
-2. The **state setter function** (`setIndex`) which can update the state variable and trigger React to render the component again.
+1. A **variável de state** (`index`) com o valor que você armazenou.
+2. A **função de definição de state** (`setIndex`) a qual pode atualizar a variável de state e acionar o React para renderizar o componente novamente.
-Here's how that happens in action:
+Aqui está como isso ocorre na prática:
```js
const [index, setIndex] = useState(0);
```
-1. **Your component renders the first time.** Because you passed `0` to `useState` as the initial value for `index`, it will return `[0, setIndex]`. React remembers `0` is the latest state value.
-2. **You update the state.** When a user clicks the button, it calls `setIndex(index + 1)`. `index` is `0`, so it's `setIndex(1)`. This tells React to remember `index` is `1` now and triggers another render.
-3. **Your component's second render.** React still sees `useState(0)`, but because React *remembers* that you set `index` to `1`, it returns `[1, setIndex]` instead.
-4. And so on!
+1. **Seu componente renderiza pela primeira vez.** Porque você passou `0` ao `useState` como o valor inicial de `index`, ele retornará `[0, setIndex]`. O React lembra-se de que `0` é o valor de state mais recente.
+2. **Você atualiza o state.** Quando um usuário clica no botão, ele chama `setIndex(index + 1)`. `index` é `0`, logo `setIndex(1)`. Isto diz ao React para se lembrar que `index` é `1` a partir de agora e aciona outra renderização.
+3. **A segunda renderização do seu componente.** O React ainda vê `useState(0)`, mas porque ele *lembra* que você definiu `index` como `1`, retorna `[1, setIndex]` em vez disto.
+4. E assim por diante!
-## Giving a component multiple state variables {/*giving-a-component-multiple-state-variables*/}
+## Dando a um componente múltiplas variáveis de state {/*giving-a-component-multiple-state-variables*/}
-You can have as many state variables of as many types as you like in one component. This component has two state variables, a number `index` and a boolean `showMore` that's toggled when you click "Show details":
+Você pode ter quantas variáveis de state de quantos tipos quiser em um componente. Esse componente tem duas variáveis de state, um número `index` e um boleano `showMore` o qual é acionado quando você clica em "Show details":
@@ -520,19 +520,19 @@ button {
-It is a good idea to have multiple state variables if their state is unrelated, like `index` and `showMore` in this example. But if you find that you often change two state variables together, it might be easier to combine them into one. For example, if you have a form with many fields, it's more convenient to have a single state variable that holds an object than state variable per field. Read [Choosing the State Structure](/learn/choosing-the-state-structure) for more tips.
+É uma boa ideia ter múltiplas variáveis de state se estas não for relacionadas, como `index` e `showMore` nesse exemplo. Mas se você perceber que frequentemente altera duas variáveis de estado juntas, pode ser mais fácil combiná-las em uma. Por exemplo, se você tem um formulário com vários campos, é mais conveniente ter uma única variável de state a qual armazena um objeto do que uma variável por campo. Leia [Escolhendo a Estrutura do State](/learn/choosing-the-state-structure) para mais dicas.
-#### How does React know which state to return? {/*how-does-react-know-which-state-to-return*/}
+#### Como o React sabe qual state retornar? {/*how-does-react-know-which-state-to-return*/}
-You might have noticed that the `useState` call does not receive any information about *which* state variable it refers to. There is no "identifier" that is passed to `useState`, so how does it know which of the state variables to return? Does it rely on some magic like parsing your functions? The answer is no.
+Você pode ter notado que a chamada ao `useState` não recebe nenhuma informação sobre *a qual* variável de state ela se refere. Não há um "identificador" que é passado ao `useState`, então como este sabe qual dessas variáveis de state retornar? Depende de alguma magia como analisar suas funções? A resposta é não.
-Instead, to enable their concise syntax, Hooks **rely on a stable call order on every render of the same component.** This works well in practice because if you follow the rule above ("only call Hooks at the top level"), Hooks will always be called in the same order. Additionally, a [linter plugin](https://www.npmjs.com/package/eslint-plugin-react-hooks) catches most mistakes.
+Em vez disso, para viabilizar sintaxe concisa, os Hooks **dependem em uma chamada estável feita em toda renderização do mesmo componente.** Isso funciona bem na prática porque se você seguir a regra acima ("só chamar Hooks no nível do topo"), os Hooks sempre serão chamados na mesma ordem. Adicionalmente, um [plugin de *linter*](https://www.npmjs.com/package/eslint-plugin-react-hooks) pega a maioria dos erros.
-Internally, React holds an array of state pairs for every component. It also maintains the current pair index, which is set to `0` before rendering. Each time you call `useState`, React gives you the next state pair and increments the index. You can read more about this mechanism in [React Hooks: Not Magic, Just Arrays.](https://medium.com/@ryardley/react-hooks-not-magic-just-arrays-cd4f1857236e)
+Internamente, o React armazena um array de pares de state para cada componente. Ele também mantêm o índice do par atual, o qual é definido como `0` antes da renderização. A cada vez que você chama `useState`, o React lhe dá o próximo par de state e incrementa o índice. Você pode ler mais sobre esse mecanismo em [React Hooks: Não é Mágica, Apenas Arrays.](https://medium.com/@ryardley/react-hooks-not-magic-just-arrays-cd4f1857236e)
-This example **doesn't use React** but it gives you an idea of how `useState` works internally:
+Esse exemplo **não usa React** mas dá uma ideia de como o `useState` funciona internamente:
@@ -540,37 +540,37 @@ This example **doesn't use React** but it gives you an idea of how `useState` wo
let componentHooks = [];
let currentHookIndex = 0;
-// How useState works inside React (simplified).
+// Como o useState funciona dentro do React (simplificado).
function useState(initialState) {
let pair = componentHooks[currentHookIndex];
if (pair) {
- // This is not the first render,
- // so the state pair already exists.
- // Return it and prepare for next Hook call.
+ // Essa não é nossa primeira renderização,
+ // então o par de state já existe.
+ // Retorne-o e prepare-se para a próxima chamada do Hook.
currentHookIndex++;
return pair;
}
- // This is the first time we're rendering,
- // so create a state pair and store it.
+ // Essa é a primeira vez em que estamos renderizando,
+ // então crie um par de state e o salve.
pair = [initialState, setState];
function setState(nextState) {
- // When the user requests a state change,
- // put the new value into the pair.
+ // Quando o usuário requisitar uma mudança de state,
+ // ponha o novo valor no par.
pair[0] = nextState;
updateDOM();
}
- // Store the pair for future renders
- // and prepare for the next Hook call.
+ // Salve o par para futuras renderizações
+ // e prepare-se para a próxima chamada do Hook.
componentHooks[currentHookIndex] = pair;
currentHookIndex++;
return pair;
}
function Gallery() {
- // Each useState() call will get the next pair.
+ // Cada chamada ao useState() irá obter o próximo par.
const [index, setIndex] = useState(0);
const [showMore, setShowMore] = useState(false);
@@ -583,8 +583,8 @@ function Gallery() {
}
let sculpture = sculptureList[index];
- // This example doesn't use React, so
- // return an output object instead of JSX.
+ // Esse exemplo não usa React, então
+ // retorne um objeto de saída em vez de JSX.
return {
onNextClick: handleNextClick,
onMoreClick: handleMoreClick,
@@ -598,13 +598,13 @@ function Gallery() {
}
function updateDOM() {
- // Reset the current Hook index
- // before rendering the component.
+ // Reinicialize o índice atual do Hook
+ // antes de renderizar o componente.
currentHookIndex = 0;
let output = Gallery();
- // Update the DOM to match the output.
- // This is the part React does for you.
+ // Atualize a DOM para igualar-se à saída.
+ // Essa é a parte que o React faz para você.
nextButton.onclick = output.onNextClick;
header.textContent = output.header;
moreButton.onclick = output.onMoreClick;
@@ -698,7 +698,7 @@ let sculptureList = [{
alt: 'A group of bronze hippo sculptures emerging from the sett sidewalk as if they were swimming.'
}];
-// Make UI match the initial state.
+// Faça a UI igualar-se ao state inicial.
updateDOM();
```
@@ -724,15 +724,15 @@ button { display: block; margin-bottom: 10px; }
-You don't have to understand it to use React, but you might find this a helpful mental model.
+Você não precisa entender isto para usar React, mas você pode considerá-lo um modelo mental útil.
-## State is isolated and private {/*state-is-isolated-and-private*/}
+## State é isolado e privado {/*state-is-isolated-and-private*/}
-State is local to a component instance on the screen. In other words, **if you render the same component twice, each copy will have completely isolated state!** Changing one of them will not affect the other.
+State é local a uma instância do componente na tela. Em outras palavras, **se você renderiza o mesmo componente duas vezes, cada cópia terá state completamente isolado!** Alterar um deles não irá afetar o outro.
-In this example, the `Gallery` component from earlier is rendered twice with no changes to its logic. Try clicking the buttons inside each of the galleries. Notice that their state is independent:
+Nesse exemplo, o componente `Gallery` de antes é renderizado duas vezes sem mudanças a sua lógica. Tente clicar nos botões dentro de cada uma das galerias. Note que seus states são independentes:
@@ -891,21 +891,21 @@ button {
-This is what makes state different from regular variables that you might declare at the top of your module. State is not tied to a particular function call or a place in the code, but it's "local" to the specific place on the screen. You rendered two `` components, so their state is stored separately.
+Isto é o que faz do state diferente de variáveis comuns que você pode declarar no topo de seu módulo. State não é atrelado a uma chamada de função em particular ou a um lugar no código, mas sim é "local" a um lugar específico na tela. Você renderizou dois componentes ``, então seus states são armazenados separadamente.
-Also notice how the `Page` component doesn't "know" anything about the `Gallery` state or even whether it has any. Unlike props, **state is fully private to the component declaring it.** The parent component can't change it. This lets you add state to any component or remove it without impacting the rest of the components.
+Perceba também como o componente `Page` não "sabe" nada sobre o state de `Gallery` ou se até ele tem algum. Diferentemente das props, **o state é completamente privado ao componente que o declara.** O componente pai não pode alterá-lo. Isso permite que você adicione state a qualquer componente ou remova-o sem impactar o restante dos componentes.
-What if you wanted both galleries to keep their states in sync? The right way to do it in React is to *remove* state from child components and add it to their closest shared parent. The next few pages will focus on organizing state of a single component, but we will return to this topic in [Sharing State Between Components.](/learn/sharing-state-between-components)
+E se você quisesse que ambas as galerias mantivessem seus states sincronizados? A maneira correta de fazer isso em React se dá por meio da *remoção* do state dos componentes filhos e armazenando-o no componente pai comum mais próximo a eles. As próximas páginas focarão na organização do state de um único componente, mas nós iremos voltar a este assunto em [Compartilhando State Entre Componentes.](/learn/sharing-state-between-components)
-* Use a state variable when a component needs to "remember" some information between renders.
-* State variables are declared by calling the `useState` Hook.
-* Hooks are special functions that start with `use`. They let you "hook into" React features like state.
-* Hooks might remind you of imports: they need to be called unconditionally. Calling Hooks, including `useState`, is only valid at the top level of a component or another Hook.
-* The `useState` Hook returns a pair of values: the current state and the function to update it.
-* You can have more than one state variable. Internally, React matches them up by their order.
-* State is private to the component. If you render it in two places, each copy gets its own state.
+* Use uma variável de state quando um componente precisa "lembrar" de alguma informação entre renderizações.
+* Variáveis de state são declaradas chamando o Hook `useState`.
+* Hooks são funções especiais que começam com `use`. Eles permitem que você "se conecte" a recursos do React como o state.
+* Hooks podem lembrá-lo de importações: eles precisam se chamados incondicionalmente. Chamar Hooks, incluindo `useState`, só é válido no nível do topo de um componente ou em outro Hook.
+* O Hook `useState` retorna um par de valores: o state atual e a função para atualizá-lo.
+* Você pode ter mais de uma variável de state. Internamente, o React as combina por sua ordem.
+* State é privado ao componente. Se você o renderizar em dois lugares, cada cópia recebe seu próprio state.
@@ -913,11 +913,11 @@ What if you wanted both galleries to keep their states in sync? The right way to
-#### Complete the gallery {/*complete-the-gallery*/}
+#### Complete a galeria {/*complete-the-gallery*/}
-When you press "Next" on the last sculpture, the code crashes. Fix the logic to prevent the crash. You may do this by adding extra logic to event handler or by disabling the button when the action is not possible.
+Quando você pressionar "Next" na última escultura, o código falha. Conserte a lógica para prevenir a falha. Você pode fazer isso adicionado lógica extra ao manipulador de eventos ou desabilitando o botão quando a ação não é possível.
-After fixing the crash, add a "Previous" button that shows the previous sculpture. It shouldn't crash on the first sculpture.
+Após consertar a falha, adicione um botão "Previous" que mostra a escultura anterior. Ele não deve falhar na primeira escultura.
@@ -1059,7 +1059,7 @@ img { width: 120px; height: 120px; }
-This adds a guarding condition inside both event handlers and disables the buttons when needed:
+Isso adiciona uma condição de guarda dentro de ambos os manipuladores de evento e desabilita os botões quando necessário:
@@ -1219,13 +1219,13 @@ img { width: 120px; height: 120px; }
-Notice how `hasPrev` and `hasNext` are used *both* for the returned JSX and inside the event handlers! This handy pattern works because event handler functions ["close over"](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures) any variables declared while rendering.
+Note como `hasPrev` e `hasNext` são usados para *ambos* a JSX retornada e dentro dos manipuladores de evento! Esse padrão prático funciona porque funções manipuladoras de eventos ["fecham sobre"](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Closures) qualquer variável declarada durante a renderização.
-#### Fix stuck form inputs {/*fix-stuck-form-inputs*/}
+#### Corrigir entradas de formulário travadas {/*fix-stuck-form-inputs*/}
-When you type into the input fields, nothing appears. It's like the input values are "stuck" with empty strings. The `value` of the first `` is set to always match the `firstName` variable, and the `value` for the second `` is set to always match the `lastName` variable. This is correct. Both inputs have `onChange` event handlers, which try to update the variables based on the latest user input (`e.target.value`). However, the variables don't seem to "remember" their values between re-renders. Fix this by using state variables instead.
+Quando você digita nos campos de entrada, nada aparece. É como se os valores de entrada estivessem "presos" com strings vazias. O `value` do primeiro `` é definido para sempre corresponder à variável `lastName`. Isso está correto. Ambas as entradas possuem manipuladores de evento `onChange`, os quais tentam atualizar as variáveis baseados na entrada mais recente do usuário (`e.target.value`). Entretanto, as variáveis não parecem se "lembrar" de seus valores entre rerrenderizações. Conserte isso usando variáveis de state como alternativa.
@@ -1274,7 +1274,7 @@ h1 { margin-top: 10px; }
-First, import `useState` from React. Then replace `firstName` and `lastName` with state variables declared by calling `useState`. Finally, replace every `firstName = ...` assignment with `setFirstName(...)`, and do the same for `lastName`. Don't forget to update `handleReset` too so that the reset button works.
+Primeiramente, importe `useState` a partir do React. Então substitua `firstName` e `lastName` com variáveis de state declaradas chamando `useState`. Por fim, substitua todas as atribuições `firstName = ...` com `setFirstName(...)`, e faça o mesmo para `lastName`. Não se esqueça de também atualizar `handleReset` para que o botão de redefinição (Reset) funcione.
@@ -1325,13 +1325,13 @@ h1 { margin-top: 10px; }
-#### Fix a crash {/*fix-a-crash*/}
+#### Conserte uma falha {/*fix-a-crash*/}
-Here is a small form that is supposed to let the user leave some feedback. When the feedback is submitted, it's supposed to display a thank-you message. However, it crashes with an error message saying "Rendered fewer hooks than expected". Can you spot the mistake and fix it?
+Aqui está um pequeno formulário o qual supostamente deve permitir que o usuário deixe alguma opinião. Quando a opinião é submetida, ele deve exibir uma mensagem de "muito obrigado". Entretanto, ele falha com uma mensagem de erro dizendo "Renderizados menos Hooks do que o esperado". Você consegue perceber o erro e consertá-lo?
-Are there any limitations on _where_ Hooks may be called? Does this component break any rules? Check if there are any comments disabling the linter checks--this is where the bugs often hide!
+Existem quaisquer limitações sobre _onde_ Hooks podem ser chamados? Esse componente quebra alguma das regras? Cheque se existem quaisquer comentários desabilitando checagens do *linter*--é aqui que bugs geralmente se escondem!
@@ -1370,9 +1370,9 @@ export default function FeedbackForm() {
-Hooks can only be called at the top level of the component function. Here, the first `isSent` definition follows this rule, but the `message` definition is nested in a condition.
+Hooks só podem ser chamados no nível do topo de uma função de componente. Aqui, a primeira definição `isSent` segue esta regra, mas a definição de `message` é aninhada em uma condição.
-Move it out of the condition to fix the issue:
+Mova-a para fora da condição para consertar o problema:
@@ -1407,9 +1407,9 @@ export default function FeedbackForm() {
-Remember, Hooks must be called unconditionally and always in the same order!
+Lembre-se, Hooks devem ser chamados incondicionalmente e sempre na mesma ordem!
-You could also remove the unnecessary `else` branch to reduce the nesting. However, it's still important that all calls to Hooks happen *before* the first `return`.
+Você poderia também remover o ramo `else` desnecessário para reduzir o aninhamento. Entretanto, é ainda importante que todas as chamadas aos Hooks aconteçam *antes* do primeiro `return`.
@@ -1444,19 +1444,19 @@ export default function FeedbackForm() {
-Try moving the second `useState` call after the `if` condition and notice how this breaks it again.
+Tente mover a segunda chamada `useState` depois da condição `if` e note como isto quebra novamente.
-If your linter is [configured for React](/learn/editor-setup#linting), you should see a lint error when you make a mistake like this. If you don't see an error when you try the faulty code locally, you need to set up linting for your project.
+Se seu *linter* está [configurado para React](/learn/editor-setup#linting), você deve ver um erro de *lint* quando faz um erro como esse. Se você não vê um erro quando tenta código falho localmente, você precisa configurar *linting* para o seu projeto.
-#### Remove unnecessary state {/*remove-unnecessary-state*/}
+#### Remova state desnecessário {/*remove-unnecessary-state*/}
-When the button is clicked, this example should ask for the user's name and then display an alert greeting them. You tried to use state to keep the name, but for some reason it always shows "Hello, !".
+Quando o botão é clicado, esse exemplo deve perguntar pelo nome do usuário e então exibir um alerta cumprimentando-o. Você tentou usar state para manter o nome, mas por alguma razão ele sempre mostra "Hello, !".
-To fix this code, remove the unnecessary state variable. (We will discuss about [why this didn't work](/learn/state-as-a-snapshot) later.)
+Para consertar esse código, remova a variável de state desnecessária. (Nós discutiremos sobre [por que isso não funcionou](/learn/state-as-a-snapshot) mais tarde.)
-Can you explain why this state variable was unnecessary?
+Você pode explicar por que essa variável de state era desnecessária?
@@ -1483,7 +1483,7 @@ export default function FeedbackForm() {
-Here is a fixed version that uses a regular `name` variable declared in the function that needs it:
+Aqui está uma verão consertada que usa uma variável normal `name` declarada na função que a necessita:
@@ -1506,7 +1506,7 @@ export default function FeedbackForm() {
-A state variable is only necessary to keep information between re-renders of a component. Within a single event handler, a regular variable will do fine. Don't introduce state variables when a regular variable works well.
+A variável de state só é necessária para manter informação entre rerrenderizações de um componente. Dentre um único manipulador de evento, uma variável comum cairá bem. Não introduza variáveis de state quando uma variável comum funciona perfeitamente.