diff --git a/beta/src/content/learn/queueing-a-series-of-state-updates.md b/beta/src/content/learn/queueing-a-series-of-state-updates.md index 4144d3623..4cecbc7e1 100644 --- a/beta/src/content/learn/queueing-a-series-of-state-updates.md +++ b/beta/src/content/learn/queueing-a-series-of-state-updates.md @@ -1,23 +1,23 @@ --- -title: Queueing a Series of State Updates +title: Poner en cola una serie de actualizaciones del estado --- -Setting a state variable will queue another render. But sometimes you might want to perform multiple operations on the value before queueing the next render. To do this, it helps to understand how React batches state updates. +Al asignar una variable de estado se pondrá en cola otro renderizado. Pero a veces, es posible que quieras realizar varias operaciones antes de poner en cola el siguiente renderizado. Para hacer esto, nos ayuda entender cómo React realiza las actualizaciones de estado por lotes. -* What "batching" is and how React uses it to process multiple state updates -* How to apply several updates to the same state variable in a row +* Qué es "la actualización por lotes (_batching_)" y cómo lo utiliza React para procesar múltiples actualizaciones del estado +* Cómo aplicar varias actualizaciones a la misma variable de estado de forma consecutiva -## React batches state updates {/*react-batches-state-updates*/} +## React actualiza el estado por lotes {/*react-batches-state-updates*/} -You might expect that clicking the "+3" button will increment the counter three times because it calls `setNumber(number + 1)` three times: +Podrías esperar que al hacer clic en el botón "+3" el contador se incremente tres veces porque llama a `setNumber(number + 1)` tres veces: @@ -47,7 +47,7 @@ h1 { display: inline-block; margin: 10px; width: 30px; text-align: center; } -However, as you might recall from the previous section, [each render's state values are fixed](/learn/state-as-a-snapshot#rendering-takes-a-snapshot-in-time), so the value of `number` inside the first render's event handler is always `0`, no matter how many times you call `setNumber(1)`: +Sin embargo, como se puede recordar de la sección anterior, [los valores del estado de cada renderizado son fijos](/learn/state-as-a-snapshot#rendering-takes-a-snapshot-in-time), por lo que el valor de `number` dentro del manejador de eventos del primer renderizado siempre es `0`, sin importar cuántas veces se llame a `setNumber(1)`: ```js setNumber(0 + 1); @@ -55,21 +55,21 @@ setNumber(0 + 1); setNumber(0 + 1); ``` -But there is one other factor at work here to discuss. **React waits until *all* code in the event handlers has run before processing your state updates.** This is why the re-render only happens *after* all these `setNumber()` calls. +Pero hay otro factor a analizar aquí. **React espera a que *todo* el código de los manejadores de eventos se haya ejecutado antes de procesar tus actualizaciones de estado.** Por ello, el rerenderizado sólo se produce *después* de todas las llamadas `setNumber()`. -This might remind you of a waiter taking an order at the restaurant. A waiter doesn't run to the kitchen at the mention of your first dish! Instead, they let you finish your order, let you make changes to it, and even take orders from other people at the table. +Esto puede recordarte a un camarero que toma nota de un pedido en un restaurante. ¡El camarero no corre a la cocina al mencionar tu primer plato! En cambio, te deja terminar tu pedido, te permite hacerle cambios e incluso toma nota de los pedidos de las otras personas en la mesa. - + -This lets you update multiple state variables--even from multiple components--without triggering too many [re-renders.](/learn/render-and-commit#re-renders-when-state-updates) But this also means that the UI won't be updated until _after_ your event handler, and any code in it, completes. This behavior, also known as **batching,** makes your React app run much faster. It also avoids dealing with confusing "half-finished" renders where only some of the variables have been updated. +Esto te permite actualizar múltiples variables del estado -incluso de múltiples componentes- sin realizar demasiados [rerenderizados.](/learn/render-and-commit#re-renders-when-state-updates) Pero esto también significa que la UI no se actualizará hasta _después_ de que tu manejador de eventos, y cualquier código en él, se complete. Este comportamiento, también conocido como **batching**, hace que tu aplicación de React se ejecute mucho más rápido. También evita tener que lidiar con confusos renderizados "a medio terminar" en los que sólo se han actualizado algunas de las variables. -**React does not batch across *multiple* intentional events like clicks**--each click is handled separately. Rest assured that React only does batching when it's generally safe to do. This ensures that, for example, if the first button click disables a form, the second click would not submit it again. +**React no agrupa *múltiples* eventos intencionados como los clics** --cada clic se maneja por separado. Puedes estar seguro de que React sólo actualizará por lotes cuando sea seguro hacerlo. Esto garantiza que, por ejemplo, si el primer clic del botón desactiva un formulario, el segundo clic no lo enviará de nuevo. -## Updating the same state variable multiple times before the next render {/*updating-the-same-state-variable-multiple-times-before-the-next-render*/} +## Actualización de la misma variable de estado varias veces antes del siguiente renderizado {/*updating-the-same-state-variable-multiple-times-before-the-next-render*/} -It is an uncommon use case, but if you would like to update the same state variable multiple times before the next render, instead of passing the *next state value* like `setNumber(number + 1)`, you can pass a *function* that calculates the next state based on the previous one in the queue, like `setNumber(n => n + 1)`. It is a way to tell React to "do something with the state value" instead of just replacing it. +Es un caso de uso poco común, pero si quieres actualizar la misma variable de estado varias veces antes del siguiente renderizado, en lugar de pasar el *siguiente valor de estado* como `setNumber(number + 1)`, puedes pasar una *función* que calcule el siguiente estado basado en el anterior en la cola, como `setNumber(n => n + 1)`. Es una forma de decirle a React que "haga algo con el valor del estado" en lugar de simplemente reemplazarlo. -Try incrementing the counter now: +Intenta incrementar el contador ahora: @@ -99,10 +99,10 @@ h1 { display: inline-block; margin: 10px; width: 30px; text-align: center; } -Here, `n => n + 1` is called an **updater function.** When you pass it to a state setter: +Aquí, `n => n + 1` se la llama una **función de actualización.** Cuando la pasas a una asignación de estado: -1. React queues this function to be processed after all the other code in the event handler has run. -2. During the next render, React goes through the queue and gives you the final updated state. +1. React pone en cola esta función para que se procese después de que se haya ejecutado el resto del código del manejador de eventos. +2. Durante el siguiente renderizado, React recorre la cola y te da el estado final actualizado. ```js setNumber(n => n + 1); @@ -110,26 +110,26 @@ setNumber(n => n + 1); setNumber(n => n + 1); ``` -Here's how React works through these lines of code while executing the event handler: +Así es como funciona React a través de estas líneas de código mientras se ejecuta el manejador de eventos: -1. `setNumber(n => n + 1)`: `n => n + 1` is a function. React adds it to a queue. -1. `setNumber(n => n + 1)`: `n => n + 1` is a function. React adds it to a queue. -1. `setNumber(n => n + 1)`: `n => n + 1` is a function. React adds it to a queue. +1. `setNumber(n => n + 1)`: `n => n + 1` es una función. React la añade a la cola. +2. `setNumber(n => n + 1)`: `n => n + 1` es una función. React la añade a la cola. +3. `setNumber(n => n + 1)`: `n => n + 1` es una función. React la añade a la cola. -When you call `useState` during the next render, React goes through the queue. The previous `number` state was `0`, so that's what React passes to the first updater function as the `n` argument. Then React takes the return value of your previous updater function and passes it to the next updater as `n`, and so on: +Cuando llamas a `useState` durante el siguiente renderizado, React recorre la cola. El estado anterior `number` era `0`, así que eso es lo que React pasa a la primera función actualizadora como el argumento `n`. Luego React toma el valor de retorno de su función actualizadora anterior y lo pasa al siguiente actualizador como `n`, y así sucesivamente: -| queued update | `n` | returns | +| actualización en cola | `n` | devuelve | |--------------|---------|-----| | `n => n + 1` | `0` | `0 + 1 = 1` | | `n => n + 1` | `1` | `1 + 1 = 2` | | `n => n + 1` | `2` | `2 + 1 = 3` | -React stores `3` as the final result and returns it from `useState`. +React almacena `3` como resultado final y lo devuelve desde `useState`. -This is why clicking "+3" in the above example correctly increments the value by 3. -### What happens if you update state after replacing it {/*what-happens-if-you-update-state-after-replacing-it*/} +Por eso, al hacer clic en "+3" en el ejemplo anterior, el valor se incrementa correctamente en 3. +### ¿Qué ocurre si se actualiza el estado después de sustituirlo? {/*what-happens-if-you-update-state-after-replacing-it*/} -What about this event handler? What do you think `number` will be in the next render? +¿Qué pasa con este manejador de eventos? ¿Qué valor crees que tendrá `number` en el próximo renderizado? ```js