Suspense para la Obtención de Datos: Cómo Obtener Durante el Renderizado

Rate this content
Bookmark

¿Qué es suspense para la obtención de datos en React? ¿Por qué el modelo de React hace que la creación de solicitudes de red durante el renderizado sea tan difícil? ¿Por qué (según el conocimiento del presentador) ninguna biblioteca además de Relay admite esto, a pesar de su gran conveniencia?


En esta charla, Robert discutirá cómo React renderiza componentes (especialmente con respecto a Suspense), y cómo construir una biblioteca de obtención de datos que funcione correctamente a la luz de esos comportamientos. Luego, con todas las piezas en su lugar, usaremos una biblioteca, @boulton/react-disposable-state, para crear nuestra propia obtención de datos compatible con suspense!

Robert Balicki
Robert Balicki
5 min
15 Nov, 2023

Video Summary and Transcription

Esta charla discute las mejores prácticas para obtener datos durante el renderizado inicial de un componente en React. Enfatiza la importancia de obtener datos con anticipación y evitar obtenerlos dos veces. La charla también destaca la necesidad de una caché externa para almacenar información sobre las llamadas a la API y el uso de una función de limpieza para evitar fugas de memoria. Además, el orador menciona su biblioteca, react-disposable-state, que se puede utilizar para hacer efectos secundarios durante el renderizado.

Available in English

1. Obtención de Datos Durante el Renderizado Inicial

Short description:

En esta charla, voy a discutir cómo obtener datos durante el renderizado inicial de un componente. Obtener durante el renderizado inicial es preferible a obtener en un efecto. Obtener por adelantado es mejor que obtener durante el renderizado. A veces, obtener durante el renderizado es la mejor opción. La obtención es solo un ejemplo de un efecto secundario que debe realizarse solo una vez y debe limpiarse. Queremos evitar obtener dos veces y en su lugar reutilizar la misma solicitud de red. Podríamos realizar otros efectos secundarios como disparar análisis o procesar números en el servidor.

♪♪ En esta charla, voy a discutir cómo obtener data durante el renderizado inicial de un componente. Pero antes de llegar a cómo obtener durante el renderizado, deberíamos discutir primero por qué. ¿Por qué queremos obtener data durante el renderizado? Bueno, obtenemos data porque la necesitamos para mostrar al usuario algo útil. Obvio. Pero, ¿por qué hacer la solicitud de red durante el renderizado? Bueno, cuanto antes obtengamos, antes podremos mostrar al usuario lo que quieren ver y mejor user experience podemos proporcionar. Así que obtener durante el renderizado inicial es preferible a obtener en un efecto, que necesariamente ocurre después de que un componente se renderiza inicialmente, a veces mucho después.

Pero, ¿es eso lo mejor que podemos hacer? ¿Qué tal obtener por adelantado? Considera un botón que, cuando se hace clic, muestra un modal, que necesita data. Podríamos iniciar la solicitud de red cuando el usuario hace clic en ese botón, lo que significa que la solicitud de red comenzará antes del renderizado inicial y podremos mostrar el contenido relevante al usuario incluso antes. Eso es genial. Vale, así que obtener por adelantado es mejor que obtener durante el renderizado. Entonces, ¿por qué obtener durante el renderizado en absoluto? Bueno, en algunos casos, es lo mejor que puedes hacer. Considera un modal que se muestra en función de alguna función opaca de algún estado de redox difícil de razonar. Básicamente, realmente no sabemos por qué se muestra este modal o bajo qué condiciones. Y en situaciones como esa, podría ser difícil determinar un momento apropiado para iniciar esa solicitud de red. Así que lo mejor que podemos hacer es obtener durante el renderizado. Como una nota al margen, nada en mi presentación es realmente sobre la obtención per se. La obtención es solo un ejemplo de un efecto secundario que debe realizarse solo una vez y debe limpiarse.

Ahora, la limpieza que queremos hacer para obtener es recoger la basura de los data que recibimos de la red si la UI ya no lo necesita para que en dispositivos de gama baja, evitemos quedarnos sin memoria. Pero más genéricamente, si un componente se renderiza dos veces, queremos evitar obtener dos veces y en su lugar reutilizar esa misma solicitud de red. Así que otro efecto secundario que debemos realizar es saber en algún lugar que ya hemos hecho una solicitud de red idéntica. Y la limpieza que queremos hacer es, después, digamos, 30 segundos, eliminar el elemento de la caché porque la próxima vez que renderizamos ese componente, realmente queremos hacer una solicitud de red. Entonces, ¿cuáles son algunos de los otros ejemplos de efectos secundarios que podríamos realizar de esta manera? Bueno, podríamos disparar algunos análisis. Podríamos hacer que el servidor comience a procesar algunos números que vamos a necesitar más tarde. Eso es prácticamente todo lo que voy a decir sobre la obtención durante el renderizado se aplica a esos también.

Vale, así que ahora finalmente podemos llegar a cómo obtener durante el renderizado. Mantengámoslo simple. ¿Podemos simplemente hacer la maldita llamada a la API durante la función de renderizado? Bueno, desafortunadamente, React y Cloud Components render function multiple times. Y en el segundo renderizado, realmente nos gustaría reutilizar esa solicitud de red anterior. Entonces, ¿podemos usar hooks? Bueno, desafortunadamente no. Si tu componente se renderiza, se suspende, y se renderiza una segunda vez, todos los hooks se crearán de nuevo para el segundo renderizado.

2. Realizando Efectos Secundarios Durante el Renderizado

Short description:

No podemos usar el estado o las referencias para almacenar información sobre la llamada a la API. El hecho de que exista una solicitud de red y deba reutilizarse debe almacenarse en algo que sobreviva a la función de renderizado. Hacer efectos secundarios solo durante el renderizado inicial requiere una caché externa. La caché debe comportarse de manera que borre y deseche el elemento después de un tiempo para evitar fugas de memoria. Si un componente se renderiza y monta, no debe ser recogido como basura, y React ejecutará una función de limpieza cuando el componente se desmonte. Con estos tres principios, puedes hacer efectos secundarios de manera segura durante el renderizado. Echa un vistazo a mi biblioteca, react-disposable-state, en el repositorio de github de Isograph.

Entonces, no podemos usar el estado o las referencias para almacenar información sobre la llamada a la API. Así que el hecho de que exista una solicitud de red y deba reutilizarse tiene que almacenarse en algo que sobreviva a la función de renderizado. Lo cual podría ser props, contexto, o un objeto global. Esto nos lleva a nuestro primer principio. Hacer efectos secundarios solo durante el renderizado inicial requiere una caché externa.

Vale. Entonces, hablemos de cómo debería comportarse esta caché. Considera ese modal. Lo renderizamos. Se suspende, lo que significa que React llama a su función de renderizado, pero no modifica el DOM para mostrar el componente al usuario. Luego, antes de que el componente se confirme, todo el árbol se desmonta porque el usuario navega a otra pantalla. En esta situación, React no nos dará ninguna indicación de que el componente nunca se montará. Así que cuando inicialmente colocamos el elemento en la caché, sería mejor también establecer un temporizador que limpie la caché y deseche el elemento, quizás, después de 30 segundos. De lo contrario, en situaciones como esa, tendremos fugas de memoria.

Vale entonces. ¿Qué pasa si el componente se renderiza y monta? Bueno, puede continuar renderizándose después, incluso después de que hayan pasado más de 30 segundos, y el componente aún necesitará acceso a esos data. Así que realmente no debería ser recogido como basura. Pero afortunadamente para nosotros, si un componente se monta, React necesariamente ejecutará una función de limpieza por lo que no necesitamos confiar en un temporizador para limpiar el elemento, lo que significa que un elemento no debería ser limpiado mientras un componente montado lo referencia, sino cuando ese componente se desmonta. Vale. Así que con estos tres principios, puedes hacer efectos secundarios de manera segura durante el renderizado. Tengo una biblioteca, react-disposable-state, en el repositorio de github de Isograph, donde expongo APIs extremadamente genéricas para hacer efectos secundarios durante el renderizado, y así sucesivamente. Espero que lo revises. Gracias. Que tengas un buen día.

Check out more articles and videos

We constantly think of articles and videos that might spark Git people interest / skill us up or help building a stellar career

Everything Beyond State Management in Stores with Pinia
Vue.js London Live 2021Vue.js London Live 2021
34 min
Everything Beyond State Management in Stores with Pinia
Top Content
When we think about Vuex, Pinia, or stores in general we often think about state management and the Flux patterns but not only do stores not always follow the Flux pattern, there is so much more about stores that make them worth using! Plugins, Devtools, server-side rendering, TypeScript integrations... Let's dive into everything beyond state management with Pinia with practical examples about plugins and Devtools to get the most out of your stores.
Using useEffect Effectively
React Advanced Conference 2022React Advanced Conference 2022
30 min
Using useEffect Effectively
Top Content
Can useEffect affect your codebase negatively? From fetching data to fighting with imperative APIs, side effects are one of the biggest sources of frustration in web app development. And let’s be honest, putting everything in useEffect hooks doesn’t help much. In this talk, we'll demystify the useEffect hook and get a better understanding of when (and when not) to use it, as well as discover how declarative effects can make effect management more maintainable in even the most complex React apps.
React Query: It’s Time to Break up with your "Global State”!
React Summit Remote Edition 2020React Summit Remote Edition 2020
30 min
React Query: It’s Time to Break up with your "Global State”!
Top Content
An increasing amount of data in our React applications is coming from remote and asynchronous sources and, even worse, continues to masquerade as "global state". In this talk, you'll get the lowdown on why most of your "global state" isn't really state at all and how React Query can help you fetch, cache and manage your asynchronous data with a fraction of the effort and code that you're used to.
Jotai Atoms Are Just Functions
React Day Berlin 2022React Day Berlin 2022
22 min
Jotai Atoms Are Just Functions
Top Content
Jotai is a state management library. We have been developing it primarily for React, but it's conceptually not tied to React. It this talk, we will see how Jotai atoms work and learn about the mental model we should have. Atoms are framework-agnostic abstraction to represent states, and they are basically just functions. Understanding the atom abstraction will help designing and implementing states in your applications with Jotai
Announcing Starbeam: Universal Reactivity
JSNation 2022JSNation 2022
27 min
Announcing Starbeam: Universal Reactivity
Starbeam is a library for building reactive data systems that integrate natively with UI frameworks such as React, Vue, Svelte or Ember. In this talk, Yehuda will announce Starbeam. He will cover the motivation for the library, and then get into the details of how Starbeam reactivity works, and most importantly, how you can use it to build reactive libraries today that will work natively in any UI framework. If you're really adventurous, he will also talk about how you could use Starbeam in an existing app using your framework of choice and talk about the benefits of using Starbeam as the state management system in your application.
Thinking in React Query
React Summit 2023React Summit 2023
22 min
Thinking in React Query
Top Content
In this talk, I'll explain React Query from a different perspective. After having maintained React Query for over two years and having answered many questions (often the same ones multiple times), I feel like there might be a fundamental understanding missing about the lib. I'll start with a quick introduction about my journey into open source and how I got to know React Query, followed by showing which mindset change is beneficial when working with React Query - how to "think in React Query". I'll have 3 major takeaways: 1) React Query is not a data fetching library It's an async state manager, we'll quickly talk about what makes a state manager, why React Query is one and what "async state" means. 2) staleTime is your best friend I've seen a bit of confusion about how to use React Query as a state manager, so I'll explain why setting staleTime is mostly all you need 3) parameters are dependencies This is important to understand to show the boundaries between client state and server state, and is essential when doing state management with React Query I will then end with a note on "separation of concerns" and about the tradeoffs of just calling `useQuery` wherever you need it in your component tree.

Workshops on related topic

Rethinking Server State with React Query
React Summit 2020React Summit 2020
96 min
Rethinking Server State with React Query
Top Content
Featured Workshop
Tanner Linsley
Tanner Linsley
The distinction between server state and client state in our applications might be a new concept for some, but it is very important to understand when delivering a top-notch user experience. Server state comes with unique problems that often sneak into our applications surprise like:
- Sharing Data across apps- Caching & Persistence- Deduping Requests- Background Updates- Managing “Stale” Data- Pagination & Incremental fetching- Memory & Garbage Collection- Optimistic Updates
Traditional “Global State” managers pretend these challenges don’t exist and this ultimately results in developers building their own on-the-fly attempts to mitigate them.
In this workshop, we will build an application that exposes these issues, allows us to understand them better, and finally turn them from challenges into features using a library designed for managing server-state called React Query.
By the end of the workshop, you will have a better understanding of server state, client state, syncing asynchronous data (mouthful, I know), and React Query.
State Management in React with Context and Hooks
React Summit Remote Edition 2021React Summit Remote Edition 2021
71 min
State Management in React with Context and Hooks
WorkshopFree
Roy Derks
Roy Derks
A lot has changed in the world of state management in React the last few years. Where Redux used to be the main library for this, the introduction of the React Context and Hook APIs has shaken things up. No longer do you need external libraries to handle both component and global state in your applications. In this workshop you'll learn the different approaches to state management in the post-Redux era of React, all based on Hooks! And as a bonus, we'll explore two upcoming state management libraries in the React ecosystem.