diff --git a/content/docs/concurrent-mode-patterns.md b/content/docs/concurrent-mode-patterns.md old mode 100644 new mode 100755 index 137d6f182..d6417ece6 --- a/content/docs/concurrent-mode-patterns.md +++ b/content/docs/concurrent-mode-patterns.md @@ -1,6 +1,6 @@ --- id: concurrent-mode-patterns -title: Concurrent UI Patterns (Experimental) +title: Patrones concurrentes en interfaces de usuario (Experimental) permalink: docs/concurrent-mode-patterns.html prev: concurrent-mode-suspense.html next: concurrent-mode-adoption.html @@ -15,63 +15,63 @@ next: concurrent-mode-adoption.html
->Caution: +> Advertencia: > ->This page describes **experimental features that are [not yet available](/docs/concurrent-mode-adoption.html) in a stable release**. Don't rely on experimental builds of React in production apps. These features may change significantly and without a warning before they become a part of React. +> Esta página describe **funcionalidades experimentales que [aún no están disponibles](/docs/concurrent-mode-adoption.html) en una versión estable**. No dependas de compilados experimentales de React en aplicaciones en producción. Estas funcionalidades pueden cambiar significativamente y sin advertencia antes de formar parte de React. > ->This documentation is aimed at early adopters and people who are curious. **If you're new to React, don't worry about these features** -- you don't need to learn them right now. For example, if you're looking for a data fetching tutorial that works today, read [this article](https://www.robinwieruch.de/react-hooks-fetch-data/) instead. +> Esta documentación está dirigida a usuarios pioneros y personas que sienten curiosidad. **Si te estás iniciando en React, no te preocupes por estas funcionalidades,** no necesitas aprenderlas inmediatamente. Por ejemplo, si estás buscando un tutorial para realizar carga de datos y que funcione hoy, lee, en cambio, [este artículo](https://www.robinwieruch.de/react-hooks-fetch-data/).
-Usually, when we update the state, we expect to see changes on the screen immediately. This makes sense because we want to keep our app responsive to user input. However, there are cases where we might prefer to **defer an update from appearing on the screen**. - -For example, if we switch from one page to another, and none of the code or data for the next screen has loaded yet, it might be frustrating to immediately see a blank page with a loading indicator. We might prefer to stay longer on the previous screen. Implementing this pattern has historically been difficult in React. Concurrent Mode offers a new set of tools to do that. - -- [Transitions](#transitions) - - [Wrapping setState in a Transition](#wrapping-setstate-in-a-transition) - - [Adding a Pending Indicator](#adding-a-pending-indicator) - - [Reviewing the Changes](#reviewing-the-changes) - - [Where Does the Update Happen?](#where-does-the-update-happen) - - [Transitions Are Everywhere](#transitions-are-everywhere) - - [Baking Transitions Into the Design System](#baking-transitions-into-the-design-system) -- [The Three Steps](#the-three-steps) - - [Default: Receded → Skeleton → Complete](#default-receded-skeleton-complete) - - [Preferred: Pending → Skeleton → Complete](#preferred-pending-skeleton-complete) - - [Wrap Lazy Features in ``](#wrap-lazy-features-in-suspense) - - [Suspense Reveal “Train”](#suspense-reveal-train) - - [Delaying a Pending Indicator](#delaying-a-pending-indicator) - - [Recap](#recap) -- [Other Patterns](#other-patterns) - - [Splitting High and Low Priority State](#splitting-high-and-low-priority-state) - - [Deferring a Value](#deferring-a-value) +Usualmente, cuando actualizamos el estado, esperamos ver los cambios en la pantalla inmediatamente. Esto tiene sentido, porque queremos que nuestra aplicación continúe respondiendo a la entrada del usuario. Sin embargo, hay casos en que quisiéramos **postergar la aparición de una actualización en la pantalla**. + +Por ejemplo, si cambiamos de una página a otra, y ni nuestro código o datos para la próxima pantalla se han cargado, puede ser frustrante ver inmediatamente una página en blanco con un indicador de carga. Podemos preferir permanecer más tiempo en la pantalla anterior. La implementación de este patrón ha sido históricamente difícil con React. El Modo Concurrente ofrece un nuevo conjunto de herramientas para hacerlo. + +- [Transiciones](#transitions) + - [Envolver setState en una transición](#wrapping-setstate-in-a-transition) + - [Añadir un indicador de espera](#adding-a-pending-indicator) + - [Revisión de los cambios](#reviewing-the-changes) + - [¿Cuándo ocurre la actualización?](#where-does-the-update-happen) + - [Las transiciones están en todos lados](#transitions-are-everywhere) + - [Incorporar las transiciones en el sistema de diseño](#baking-transitions-into-the-design-system) +- [Los tres pasos](#the-three-steps) + - [Predeterminado: Retirada → Esqueleto → Completado](#default-receded-skeleton-complete) + - [Preferido: Pendiente → Esqueleto → Completado](#preferred-pending-skeleton-complete) + - [Envolver funcionalidad diferida en ``](#wrap-lazy-features-in-suspense) + - ["Tren" de revelación de Suspense](#suspense-reveal-train) + - [Demora de un indicador de estado Pendiente](#delaying-a-pending-indicator) + - [Recapitulación](#recap) +- [Otros patrones](#other-patterns) + - [Separación del estado de alta y baja prioridad](#splitting-high-and-low-priority-state) + - [Postergar un valor](#deferring-a-value) - [SuspenseList](#suspenselist) -- [Next Steps](#next-steps) +- [Próximos pasos](#next-steps) -## Transitions {#transitions} +## Transiciones {#transitions} -Let's revisit [this demo](https://codesandbox.io/s/infallible-feather-xjtbu) from the previous page about [Suspense for Data Fetching](/docs/concurrent-mode-suspense.html). +Revisitemos [este demo](https://codesandbox.io/s/infallible-feather-xjtbu) de la página anterior acerca de [Suspense para la carga de datos](/docs/concurrent-mode-suspense.html). -When we click the "Next" button to switch the active profile, the existing page data immediately disappears, and we see the loading indicator for the whole page again. We can call this an "undesirable" loading state. **It would be nice if we could "skip" it and wait for some content to load before transitioning to the new screen.** +Cuando hacemos clic en el botón "Next" para cambiar el perfil activo, los datos de la página existente desaparecen inmediatamente y vemos el indicador de carga para todo la página nuevamente. Podemos llamar a esto un estado de carga "no deseable". **Sería bueno si pudiéramos "saltárnoslo" y esperar a que cargue algún contenido antes de hacer la transición a la nueva pantalla.** -React offers a new built-in `useTransition()` Hook to help with this. +React ofrece un nuevo Hook integrado llamado `useTransition()` para ayudar con esto. -We can use it in three steps. +Podemos usarlo en tres pasos. -First, we'll make sure that we're actually using Concurrent Mode. We'll talk more about [adopting Concurrent Mode](/docs/concurrent-mode-adoption.html) later, but for now it's sufficient to know that we need to use `ReactDOM.createRoot()` rather than `ReactDOM.render()` for this feature to work: +Primero, nos aseguraremos de que estamos realmente usando el Modo Concurrente. Hablaremos más luego sobre como [adoptar el Modo Concurrente](/docs/concurrent-mode-adoption.html), pero por ahora es suficiente saber que necesitamos utilizar `ReactDOM.createRoot()` en lugar de `ReactDOM.render()` para que esto funcione: ```js const rootElement = document.getElementById("root"); -// Opt into Concurrent Mode +// Optar por el Modo Concurrente ReactDOM.createRoot(rootElement).render(); ``` -Next, we'll add an import for the `useTransition` Hook from React: +A continuación, importaremos el Hook `useTransition` desde React: ```js import React, { useState, useTransition, Suspense } from "react"; ``` -Finally, we'll use it inside the `App` component: +Para finalizar, lo utilizaremos dentro del componente `App`: ```js{3-5} function App() { @@ -82,18 +82,18 @@ function App() { // ... ``` -**By itself, this code doesn't do anything yet.** We will need to use this Hook's return values to set up our state transition. There are two values returned from `useTransition`: +**Por sí solo, este código no hace nada aún.** Necesitaremos utilizar los valor de retorno de este Hook para establecer nuestra transición de estado. Hay dos valores retornados por `useTransition`: -* `startTransition` is a function. We'll use it to tell React *which* state update we want to defer. -* `isPending` is a boolean. It's React telling us whether that transition is ongoing at the moment. +* `startTransition` es una función. La usaremos para decirle a React *qué* actualización de estado queremos postergar. +* `isPending` es un booleano. Es React diciéndonos si esa transición está ocurriendo actualmente. -We will use them right below. +Los usaremos debajo. -Note we passed a configuration object to `useTransition`. Its `timeoutMs` property specifies **how long we're willing to wait for the transition to finish**. By passing `{timeoutMs: 3000}`, we say "If the next profile takes more than 3 seconds to load, show the big spinner -- but before that timeout it's okay to keep showing the previous screen". +Nota que pasamos un objeto de configuración para `useTransition`. Su propiedad `timeoutMs` especifica *cuánto tiempo estamos dispuestos a esperar para que la transición termine**. Al pasar `{timeoutMs: 3000}` estamos diciendo: "Si el próximo perfil toma más de 3 segundos en cargar, muestra este gran _spinner_, pero antes de ese tiempo está bien seguir mostrando la pantalla anterior". -### Wrapping setState in a Transition {#wrapping-setstate-in-a-transition} +### Envolver setState en una transición {#wrapping-setstate-in-a-transition} -Our "Next" button click handler sets the state that switches the current profile in the state: +Nuestro manejador del evento del clic del botón "Next" realiza la actualización que cambia el perfil actual en el estado: ```js{4}