From 5733c7296efc8956f91d3f1bf72d6ccd95e7f923 Mon Sep 17 00:00:00 2001 From: leonardobrzz Date: Thu, 5 Nov 2026 13:14:53 -0300 Subject: [PATCH] =?UTF-8?q?docs:=20translate=20useReducer.md=20to=20Portug?= =?UTF-8?q?u=C3=AAs=20(Brasil)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/content/reference/react/useReducer.md | 204 +++++++++++----------- 1 file changed, 102 insertions(+), 102 deletions(-) diff --git a/src/content/reference/react/useReducer.md b/src/content/reference/react/useReducer.md index 404ebb0877..f90c73e661 100644 --- a/src/content/reference/react/useReducer.md +++ b/src/content/reference/react/useReducer.md @@ -4,7 +4,7 @@ title: useReducer -`useReducer` is a React Hook that lets you add a [reducer](/learn/extracting-state-logic-into-a-reducer) to your component. +`useReducer` é um Hook do React que permite adicionar um [reducer](/learn/extracting-state-logic-into-a-reducer) ao seu componente. ```js const [state, dispatch] = useReducer(reducer, initialArg, init?) @@ -16,11 +16,11 @@ const [state, dispatch] = useReducer(reducer, initialArg, init?) --- -## Reference {/*reference*/} +## Referência {/*reference*/} ### `useReducer(reducer, initialArg, init?)` {/*usereducer*/} -Call `useReducer` at the top level of your component to manage its state with a [reducer.](/learn/extracting-state-logic-into-a-reducer) +Chame `useReducer` no nível raiz do seu componente para gerenciar o state dele com um [reducer.](/learn/extracting-state-logic-into-a-reducer) ```js import { useReducer } from 'react'; @@ -34,32 +34,32 @@ function MyComponent() { // ... ``` -[See more examples below.](#usage) +[Veja mais exemplos abaixo.](#usage) -#### Parameters {/*parameters*/} +#### Parâmetros {/*parameters*/} -* `reducer`: The reducer function that specifies how the state gets updated. It must be pure, should take the state and action as arguments, and should return the next state. State and action can be of any types. -* `initialArg`: The value from which the initial state is calculated. It can be a value of any type. How the initial state is calculated from it depends on the next `init` argument. -* **optional** `init`: The initializer function that should return the initial state. If it's not specified, the initial state is set to `initialArg`. Otherwise, the initial state is set to the result of calling `init(initialArg)`. +* `reducer`: A função reducer que especifica como o state é atualizado. Ela deve ser pura, deve receber o state e a action como argumentos e deve retornar o próximo state. O state e a action podem ser de qualquer tipo. +* `initialArg`: O valor a partir do qual o state inicial é calculado. Pode ser um valor de qualquer tipo. Como o state inicial é calculado a partir dele depende do próximo argumento, `init`. +* **opcional** `init`: A função inicializadora que deve retornar o state inicial. Se não for especificada, o state inicial será `initialArg`. Caso contrário, o state inicial será o resultado da chamada `init(initialArg)`. -#### Returns {/*returns*/} +#### Retorna {/*returns*/} -`useReducer` returns an array with exactly two values: +`useReducer` retorna um array com exatamente dois valores: -1. The current state. During the first render, it's set to `init(initialArg)` or `initialArg` (if there's no `init`). -2. The [`dispatch` function](#dispatch) that lets you update the state to a different value and trigger a re-render. +1. O state atual. Durante a primeira renderização, ele é definido como `init(initialArg)` ou `initialArg` (se não houver `init`). +2. A [função `dispatch`](#dispatch), que permite atualizar o state para um valor diferente e acionar uma nova renderização. -#### Caveats {/*caveats*/} +#### Ressalvas {/*caveats*/} -* `useReducer` is a Hook, so you can only call it **at the top level of your component** or your own Hooks. You can't call it inside loops or conditions. If you need that, extract a new component and move the state into it. -* The `dispatch` function has a stable identity, so you will often see it omitted from Effect dependencies, but including it will not cause the Effect to fire. If the linter lets you omit a dependency without errors, it is safe to do. [Learn more about removing Effect dependencies.](/learn/removing-effect-dependencies#move-dynamic-objects-and-functions-inside-your-effect) -* In Strict Mode, React will **call your reducer and initializer twice** in order to [help you find accidental impurities.](#my-reducer-or-initializer-function-runs-twice) This is development-only behavior and does not affect production. If your reducer and initializer are pure (as they should be), this should not affect your logic. The result from one of the calls is ignored. +* `useReducer` é um Hook, então você só pode chamá-lo **no nível raiz do seu componente** ou nos seus próprios Hooks. Você não pode chamá-lo dentro de loops ou condições. Se precisar disso, extraia um novo componente e mova o state para ele. +* A função `dispatch` tem uma identidade estável, então você frequentemente a verá omitida das dependências de Effect, mas incluí-la não fará com que o Effect dispare. Se o linter permitir que você omita uma dependência sem erros, é seguro fazê-lo. [Saiba mais sobre como remover dependências de Effect.](/learn/removing-effect-dependencies#move-dynamic-objects-and-functions-inside-your-effect) +* No Modo Strict, o React **chamará seu reducer e sua função inicializadora duas vezes** para [ajudá-lo a encontrar impurezas acidentais.](#my-reducer-or-initializer-function-runs-twice) Este é um comportamento apenas de desenvolvimento e não afeta a produção. Se seu reducer e sua função inicializadora forem puros (como deveriam ser), isso não deve afetar sua lógica. O resultado de uma das chamadas é ignorado. --- -### `dispatch` function {/*dispatch*/} +### Função `dispatch` {/*dispatch*/} -The `dispatch` function returned by `useReducer` lets you update the state to a different value and trigger a re-render. You need to pass the action as the only argument to the `dispatch` function: +A função `dispatch` retornada por `useReducer` permite atualizar o state para um valor diferente e acionar uma nova renderização. Você precisa passar a action como único argumento para a função `dispatch`: ```js const [state, dispatch] = useReducer(reducer, { age: 42 }); @@ -69,31 +69,31 @@ function handleClick() { // ... ``` -React will set the next state to the result of calling the `reducer` function you've provided with the current `state` and the action you've passed to `dispatch`. +O React definirá o próximo state como o resultado da chamada da função `reducer` que você forneceu, com o `state` atual e a action que você passou para `dispatch`. -#### Parameters {/*dispatch-parameters*/} +#### Parâmetros {/*dispatch-parameters*/} -* `action`: The action performed by the user. It can be a value of any type. By convention, an action is usually an object with a `type` property identifying it and, optionally, other properties with additional information. +* `action`: A ação realizada pelo usuário. Pode ser um valor de qualquer tipo. Por convenção, uma action costuma ser um objeto com uma propriedade `type` que a identifica e, opcionalmente, outras propriedades com informações adicionais. -#### Returns {/*dispatch-returns*/} +#### Retorna {/*dispatch-returns*/} -`dispatch` functions do not have a return value. +Funções `dispatch` não têm valor de retorno. -#### Caveats {/*setstate-caveats*/} +#### Ressalvas {/*setstate-caveats*/} -* The `dispatch` function **only updates the state variable for the *next* render**. If you read the state variable after calling the `dispatch` function, [you will still get the old value](#ive-dispatched-an-action-but-logging-gives-me-the-old-state-value) that was on the screen before your call. +* A função `dispatch` **só atualiza a variável de state para a *próxima* renderização**. Se você ler a variável de state depois de chamar a função `dispatch`, [você ainda obterá o valor antigo](#ive-dispatched-an-action-but-logging-gives-me-the-old-state-value) que estava na tela antes da sua chamada. -* If the new value you provide is identical to the current `state`, as determined by an [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison, React will **skip re-rendering the component and its children.** This is an optimization. React may still need to call your component before ignoring the result, but it shouldn't affect your code. +* Se o novo valor que você fornecer for idêntico ao `state` atual, conforme determinado por uma comparação [`Object.is`](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Object/is), o React **pulará a nova renderização do componente e de seus filhos.** Isso é uma otimização. O React ainda pode precisar chamar seu componente antes de ignorar o resultado, mas isso não deve afetar seu código. -* React [batches state updates.](/learn/queueing-a-series-of-state-updates) It updates the screen **after all the event handlers have run** and have called their `set` functions. This prevents multiple re-renders during a single event. In the rare case that you need to force React to update the screen earlier, for example to access the DOM, you can use [`flushSync`.](/reference/react-dom/flushSync) +* O React [processa atualizações de state em lote.](/learn/queueing-a-series-of-state-updates) Ele atualiza a tela **depois que todos os manipuladores de eventos forem executados** e tiverem chamado suas funções `set`. Isso evita múltiplas renderizações durante um único evento. No raro caso de você precisar forçar o React a atualizar a tela mais cedo, por exemplo para acessar o DOM, você pode usar [`flushSync`.](/reference/react-dom/flushSync) --- -## Usage {/*usage*/} +## Uso {/*usage*/} -### Adding a reducer to a component {/*adding-a-reducer-to-a-component*/} +### Adicionando um reducer a um componente {/*adding-a-reducer-to-a-component*/} -Call `useReducer` at the top level of your component to manage state with a [reducer.](/learn/extracting-state-logic-into-a-reducer) +Chame `useReducer` no nível raiz do seu componente para gerenciar o state com um [reducer.](/learn/extracting-state-logic-into-a-reducer) ```js [[1, 8, "state"], [2, 8, "dispatch"], [4, 8, "reducer"], [3, 8, "{ age: 42 }"]] import { useReducer } from 'react'; @@ -107,12 +107,12 @@ function MyComponent() { // ... ``` -`useReducer` returns an array with exactly two items: +`useReducer` retorna um array com exatamente dois itens: -1. The current state of this state variable, initially set to the initial state you provided. -2. The `dispatch` function that lets you change it in response to interaction. +1. O state atual desta variável de state, inicialmente definido como o state inicial que você forneceu. +2. A função `dispatch`, que permite alterá-lo em resposta a uma interação. -To update what's on the screen, call `dispatch` with an object representing what the user did, called an *action*: +Para atualizar o que está na tela, chame `dispatch` com um objeto que representa o que o usuário fez, chamado de *action*: ```js [[2, 2, "dispatch"]] function handleClick() { @@ -120,7 +120,7 @@ function handleClick() { } ``` -React will pass the current state and the action to your reducer function. Your reducer will calculate and return the next state. React will store that next state, render your component with it, and update the UI. +O React passará o state atual e a action para a sua função reducer. Seu reducer calculará e retornará o próximo state. O React armazenará esse próximo state, renderizará seu componente com ele e atualizará a UI. @@ -158,13 +158,13 @@ button { display: block; margin-top: 10px; } -`useReducer` is very similar to [`useState`](/reference/react/useState), but it lets you move the state update logic from event handlers into a single function outside of your component. Read more about [choosing between `useState` and `useReducer`.](/learn/extracting-state-logic-into-a-reducer#comparing-usestate-and-usereducer) +`useReducer` é muito parecido com [`useState`](/reference/react/useState), mas permite mover a lógica de atualização do state dos manipuladores de eventos para uma única função fora do seu componente. Leia mais sobre [como escolher entre `useState` e `useReducer`.](/learn/extracting-state-logic-into-a-reducer#comparing-usestate-and-usereducer) --- -### Writing the reducer function {/*writing-the-reducer-function*/} +### Escrevendo a função reducer {/*writing-the-reducer-function*/} -A reducer function is declared like this: +Uma função reducer é declarada assim: ```js function reducer(state, action) { @@ -172,7 +172,7 @@ function reducer(state, action) { } ``` -Then you need to fill in the code that will calculate and return the next state. By convention, it is common to write it as a [`switch` statement.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch) For each `case` in the `switch`, calculate and return some next state. +Depois, você precisa preencher o código que vai calcular e retornar o próximo state. Por convenção, é comum escrevê-lo como uma [instrução `switch`.](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Statements/switch) Para cada `case` do `switch`, calcule e retorne algum próximo state. ```js {4-7,10-13} function reducer(state, action) { @@ -194,7 +194,7 @@ function reducer(state, action) { } ``` -Actions can have any shape. By convention, it's common to pass objects with a `type` property identifying the action. It should include the minimal necessary information that the reducer needs to compute the next state. +As actions podem ter qualquer formato. Por convenção, é comum passar objetos com uma propriedade `type` que identifica a action. Ela deve incluir as informações mínimas necessárias para o reducer calcular o próximo state. ```js {5,9-12} function Form() { @@ -213,31 +213,31 @@ function Form() { // ... ``` -The action type names are local to your component. [Each action describes a single interaction, even if that leads to multiple changes in data.](/learn/extracting-state-logic-into-a-reducer#writing-reducers-well) The shape of the state is arbitrary, but usually it'll be an object or an array. +Os nomes dos tipos de action são locais ao seu componente. [Cada action descreve uma única interação, mesmo que isso leve a várias alterações nos dados.](/learn/extracting-state-logic-into-a-reducer#writing-reducers-well) O formato do state é arbitrário, mas geralmente será um objeto ou um array. -Read [extracting state logic into a reducer](/learn/extracting-state-logic-into-a-reducer) to learn more. +Leia [extraindo a lógica de state para um reducer](/learn/extracting-state-logic-into-a-reducer) para saber mais. -State is read-only. Don't modify any objects or arrays in state: +O state é somente leitura. Não modifique nenhum objeto ou array no state: ```js {4,5} function reducer(state, action) { switch (action.type) { case 'incremented_age': { - // 🚩 Don't mutate an object in state like this: + // 🚩 Não mute um objeto no state assim: state.age = state.age + 1; return state; } ``` -Instead, always return new objects from your reducer: +Em vez disso, sempre retorne novos objetos do seu reducer: ```js {4-8} function reducer(state, action) { switch (action.type) { case 'incremented_age': { - // ✅ Instead, return a new object + // ✅ Em vez disso, retorne um novo objeto return { ...state, age: state.age + 1 @@ -245,15 +245,15 @@ function reducer(state, action) { } ``` -Read [updating objects in state](/learn/updating-objects-in-state) and [updating arrays in state](/learn/updating-arrays-in-state) to learn more. +Leia [atualizando objetos no state](/learn/updating-objects-in-state) e [atualizando arrays no state](/learn/updating-arrays-in-state) para saber mais. - + -#### Form (object) {/*form-object*/} +#### Formulário (objeto) {/*form-object*/} -In this example, the reducer manages a state object with two fields: `name` and `age`. +Neste exemplo, o reducer gerencia um objeto de state com dois campos: `name` e `age`. @@ -317,9 +317,9 @@ button { display: block; margin-top: 10px; } -#### Todo list (array) {/*todo-list-array*/} +#### Lista de tarefas (array) {/*todo-list-array*/} -In this example, the reducer manages an array of tasks. The array needs to be updated [without mutation.](/learn/updating-arrays-in-state) +Neste exemplo, o reducer gerencia um array de tarefas. O array precisa ser atualizado [sem mutação.](/learn/updating-arrays-in-state) @@ -510,9 +510,9 @@ ul, li { margin: 0; padding: 0; } -#### Writing concise update logic with Immer {/*writing-concise-update-logic-with-immer*/} +#### Escrevendo lógica de atualização concisa com Immer {/*writing-concise-update-logic-with-immer*/} -If updating arrays and objects without mutation feels tedious, you can use a library like [Immer](https://github.com/immerjs/use-immer#useimmerreducer) to reduce repetitive code. Immer lets you write concise code as if you were mutating objects, but under the hood it performs immutable updates: +Se atualizar arrays e objetos sem mutação parecer trabalhoso, você pode usar uma biblioteca como o [Immer](https://github.com/immerjs/use-immer#useimmerreducer) para reduzir código repetitivo. O Immer permite escrever código conciso como se você estivesse mutando objetos, mas, por baixo dos panos, ele realiza atualizações imutáveis: @@ -724,9 +724,9 @@ ul, li { margin: 0; padding: 0; } --- -### Avoiding recreating the initial state {/*avoiding-recreating-the-initial-state*/} +### Evitando recriar o state inicial {/*avoiding-recreating-the-initial-state*/} -React saves the initial state once and ignores it on the next renders. +O React salva o state inicial uma vez e o ignora nas próximas renderizações. ```js function createInitialState(username) { @@ -738,9 +738,9 @@ function TodoList({ username }) { // ... ``` -Although the result of `createInitialState(username)` is only used for the initial render, you're still calling this function on every render. This can be wasteful if it's creating large arrays or performing expensive calculations. +Embora o resultado de `createInitialState(username)` seja usado apenas na renderização inicial, você ainda está chamando essa função em toda renderização. Isso pode ser um desperdício se ela estiver criando arrays grandes ou realizando cálculos custosos. -To solve this, you may **pass it as an _initializer_ function** to `useReducer` as the third argument instead: +Para resolver isso, você pode **passá-la como uma função _inicializadora_** para `useReducer`, como terceiro argumento: ```js {6} function createInitialState(username) { @@ -752,15 +752,15 @@ function TodoList({ username }) { // ... ``` -Notice that you’re passing `createInitialState`, which is the *function itself*, and not `createInitialState()`, which is the result of calling it. This way, the initial state does not get re-created after initialization. +Observe que você está passando `createInitialState`, que é a *própria função*, e não `createInitialState()`, que é o resultado de chamá-la. Dessa forma, o state inicial não é recriado após a inicialização. -In the above example, `createInitialState` takes a `username` argument. If your initializer doesn't need any information to compute the initial state, you may pass `null` as the second argument to `useReducer`. +No exemplo acima, `createInitialState` recebe um argumento `username`. Se sua função inicializadora não precisar de nenhuma informação para calcular o state inicial, você pode passar `null` como segundo argumento para `useReducer`. - + -#### Passing the initializer function {/*passing-the-initializer-function*/} +#### Passando a função inicializadora {/*passing-the-initializer-function*/} -This example passes the initializer function, so the `createInitialState` function only runs during initialization. It does not run when component re-renders, such as when you type into the input. +Este exemplo passa a função inicializadora, então a função `createInitialState` só é executada durante a inicialização. Ela não é executada quando o componente renderiza novamente, como quando você digita no campo de texto. @@ -846,9 +846,9 @@ export default function TodoList({ username }) { -#### Passing the initial state directly {/*passing-the-initial-state-directly*/} +#### Passando o state inicial diretamente {/*passing-the-initial-state-directly*/} -This example **does not** pass the initializer function, so the `createInitialState` function runs on every render, such as when you type into the input. There is no observable difference in behavior, but this code is less efficient. +Este exemplo **não** passa a função inicializadora, então a função `createInitialState` é executada em toda renderização, como quando você digita no campo de texto. Não há diferença perceptível no comportamento, mas este código é menos eficiente. @@ -937,28 +937,28 @@ export default function TodoList({ username }) { --- -## Troubleshooting {/*troubleshooting*/} +## Solução de problemas {/*troubleshooting*/} -### I've dispatched an action, but logging gives me the old state value {/*ive-dispatched-an-action-but-logging-gives-me-the-old-state-value*/} +### Eu despachei uma action, mas o log mostra o valor antigo do state {/*ive-dispatched-an-action-but-logging-gives-me-the-old-state-value*/} -Calling the `dispatch` function **does not change state in the running code**: +Chamar a função `dispatch` **não altera o state no código que já está em execução**: ```js {4,5,8} function handleClick() { console.log(state.age); // 42 - dispatch({ type: 'incremented_age' }); // Request a re-render with 43 - console.log(state.age); // Still 42! + dispatch({ type: 'incremented_age' }); // Solicita uma nova renderização com 43 + console.log(state.age); // Ainda 42! setTimeout(() => { - console.log(state.age); // Also 42! + console.log(state.age); // Também 42! }, 5000); } ``` -This is because [states behaves like a snapshot.](/learn/state-as-a-snapshot) Updating state requests another render with the new state value, but does not affect the `state` JavaScript variable in your already-running event handler. +Isso acontece porque [o state se comporta como uma foto instantânea.](/learn/state-as-a-snapshot) Atualizar o state solicita outra renderização com o novo valor do state, mas não afeta a variável JavaScript `state` no seu manipulador de eventos que já está em execução. -If you need to guess the next state value, you can calculate it manually by calling the reducer yourself: +Se você precisar prever o próximo valor do state, pode calculá-lo manualmente chamando o reducer você mesmo: ```js const action = { type: 'incremented_age' }; @@ -971,20 +971,20 @@ console.log(nextState); // { age: 43 } --- -### I've dispatched an action, but the screen doesn't update {/*ive-dispatched-an-action-but-the-screen-doesnt-update*/} +### Eu despachei uma action, mas a tela não atualiza {/*ive-dispatched-an-action-but-the-screen-doesnt-update*/} -React will **ignore your update if the next state is equal to the previous state,** as determined by an [`Object.is`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is) comparison. This usually happens when you change an object or an array in state directly: +O React **ignorará sua atualização se o próximo state for igual ao state anterior,** conforme determinado por uma comparação [`Object.is`](https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Object/is). Isso geralmente acontece quando você altera diretamente um objeto ou array no state: ```js {4-5,9-10} function reducer(state, action) { switch (action.type) { case 'incremented_age': { - // 🚩 Wrong: mutating existing object + // 🚩 Errado: mutando o objeto existente state.age++; return state; } case 'changed_name': { - // 🚩 Wrong: mutating existing object + // 🚩 Errado: mutando o objeto existente state.name = action.nextName; return state; } @@ -993,20 +993,20 @@ function reducer(state, action) { } ``` -You mutated an existing `state` object and returned it, so React ignored the update. To fix this, you need to ensure that you're always [updating objects in state](/learn/updating-objects-in-state) and [updating arrays in state](/learn/updating-arrays-in-state) instead of mutating them: +Você mutou um objeto `state` existente e o retornou, então o React ignorou a atualização. Para corrigir isso, garanta que você está sempre [atualizando objetos no state](/learn/updating-objects-in-state) e [atualizando arrays no state](/learn/updating-arrays-in-state) em vez de mutá-los: ```js {4-8,11-15} function reducer(state, action) { switch (action.type) { case 'incremented_age': { - // ✅ Correct: creating a new object + // ✅ Correto: criando um novo objeto return { ...state, age: state.age + 1 }; } case 'changed_name': { - // ✅ Correct: creating a new object + // ✅ Correto: criando um novo objeto return { ...state, name: action.nextName @@ -1019,29 +1019,29 @@ function reducer(state, action) { --- -### A part of my reducer state becomes undefined after dispatching {/*a-part-of-my-reducer-state-becomes-undefined-after-dispatching*/} +### Uma parte do state do meu reducer fica undefined depois do dispatch {/*a-part-of-my-reducer-state-becomes-undefined-after-dispatching*/} -Make sure that every `case` branch **copies all of the existing fields** when returning the new state: +Garanta que cada ramo `case` **copie todos os campos existentes** ao retornar o novo state: ```js {5} function reducer(state, action) { switch (action.type) { case 'incremented_age': { return { - ...state, // Don't forget this! + ...state, // Não esqueça disso! age: state.age + 1 }; } // ... ``` -Without `...state` above, the returned next state would only contain the `age` field and nothing else. +Sem o `...state` acima, o próximo state retornado conteria apenas o campo `age` e mais nada. --- -### My entire reducer state becomes undefined after dispatching {/*my-entire-reducer-state-becomes-undefined-after-dispatching*/} +### Todo o state do meu reducer fica undefined depois do dispatch {/*my-entire-reducer-state-becomes-undefined-after-dispatching*/} -If your state unexpectedly becomes `undefined`, you're likely forgetting to `return` state in one of the cases, or your action type doesn't match any of the `case` statements. To find why, throw an error outside the `switch`: +Se o seu state se tornar `undefined` inesperadamente, provavelmente você esqueceu de fazer `return` do state em um dos casos, ou o tipo da sua action não corresponde a nenhuma das instruções `case`. Para descobrir o motivo, lance um erro fora do `switch`: ```js {10} function reducer(state, action) { @@ -1057,42 +1057,42 @@ function reducer(state, action) { } ``` -You can also use a static type checker like TypeScript to catch such mistakes. +Você também pode usar um verificador de tipos estático, como o TypeScript, para detectar esse tipo de erro. --- -### I'm getting an error: "Too many re-renders" {/*im-getting-an-error-too-many-re-renders*/} +### Estou recebendo um erro: "Too many re-renders" {/*im-getting-an-error-too-many-re-renders*/} -You might get an error that says: `Too many re-renders. React limits the number of renders to prevent an infinite loop.` Typically, this means that you're unconditionally dispatching an action *during render*, so your component enters a loop: render, dispatch (which causes a render), render, dispatch (which causes a render), and so on. Very often, this is caused by a mistake in specifying an event handler: +Você pode receber um erro que diz: `Too many re-renders. React limits the number of renders to prevent an infinite loop.` Normalmente, isso significa que você está despachando uma action incondicionalmente *durante a renderização*, então seu componente entra em um loop: renderiza, despacha (o que causa uma renderização), renderiza, despacha (o que causa uma renderização) e assim por diante. Muitas vezes, isso é causado por um erro ao especificar um manipulador de eventos: ```js {1-2} -// 🚩 Wrong: calls the handler during render +// 🚩 Errado: chama o manipulador durante a renderização return -// ✅ Correct: passes down the event handler +// ✅ Correto: passa o manipulador de eventos adiante return -// ✅ Correct: passes down an inline function +// ✅ Correto: passa uma função inline adiante return ``` -If you can't find the cause of this error, click on the arrow next to the error in the console and look through the JavaScript stack to find the specific `dispatch` function call responsible for the error. +Se você não conseguir encontrar a causa desse erro, clique na seta ao lado do erro no console e examine a pilha do JavaScript para encontrar a chamada específica da função `dispatch` responsável pelo erro. --- -### My reducer or initializer function runs twice {/*my-reducer-or-initializer-function-runs-twice*/} +### Minha função reducer ou inicializadora é executada duas vezes {/*my-reducer-or-initializer-function-runs-twice*/} -In [Strict Mode](/reference/react/StrictMode), React will call your reducer and initializer functions twice. This shouldn't break your code. +No [Modo Strict](/reference/react/StrictMode), o React chamará suas funções reducer e inicializadora duas vezes. Isso não deve quebrar seu código. -This **development-only** behavior helps you [keep components pure.](/learn/keeping-components-pure) React uses the result of one of the calls, and ignores the result of the other call. As long as your component, initializer, and reducer functions are pure, this shouldn't affect your logic. However, if they are accidentally impure, this helps you notice the mistakes. +Este comportamento **apenas de desenvolvimento** ajuda você a [manter os componentes puros.](/learn/keeping-components-pure) O React usa o resultado de uma das chamadas e ignora o resultado da outra. Desde que suas funções de componente, inicializadora e reducer sejam puras, isso não deve afetar sua lógica. Porém, se elas forem impuras por acidente, isso ajuda você a perceber os erros. -For example, this impure reducer function mutates an array in state: +Por exemplo, esta função reducer impura muta um array no state: ```js {4-6} function reducer(state, action) { switch (action.type) { case 'added_todo': { - // 🚩 Mistake: mutating state + // 🚩 Erro: mutando o state state.todos.push({ id: nextId++, text: action.text }); return state; } @@ -1101,13 +1101,13 @@ function reducer(state, action) { } ``` -Because React calls your reducer function twice, you'll see the todo was added twice, so you'll know that there is a mistake. In this example, you can fix the mistake by [replacing the array instead of mutating it](/learn/updating-arrays-in-state#adding-to-an-array): +Como o React chama sua função reducer duas vezes, você verá que a tarefa foi adicionada duas vezes, então saberá que há um erro. Neste exemplo, você pode corrigir o erro [substituindo o array em vez de mutá-lo](/learn/updating-arrays-in-state#adding-to-an-array): ```js {4-11} function reducer(state, action) { switch (action.type) { case 'added_todo': { - // ✅ Correct: replacing with new state + // ✅ Correto: substituindo por um novo state return { ...state, todos: [ @@ -1121,6 +1121,6 @@ function reducer(state, action) { } ``` -Now that this reducer function is pure, calling it an extra time doesn't make a difference in behavior. This is why React calling it twice helps you find mistakes. **Only component, initializer, and reducer functions need to be pure.** Event handlers don't need to be pure, so React will never call your event handlers twice. +Agora que esta função reducer é pura, chamá-la uma vez a mais não faz diferença no comportamento. É por isso que o React chamá-la duas vezes ajuda você a encontrar erros. **Apenas funções de componente, inicializadoras e reducers precisam ser puras.** Manipuladores de eventos não precisam ser puros, então o React nunca chamará seus manipuladores de eventos duas vezes. -Read [keeping components pure](/learn/keeping-components-pure) to learn more. +Leia [mantendo os componentes puros](/learn/keeping-components-pure) para saber mais.