Gestión del Estado en React con Valtio

Rate this content
Bookmark

En esta charla, exploraremos cómo Valtio puede simplificar la gestión de estado de tu React proporcionando una solución minimalista y de alto rendimiento. Cubriremos los fundamentos de Valtio, incluyendo cómo crear y actualizar una tienda y cómo acceder y modificar la tienda desde tus componentes. También nos adentraremos en algunas características avanzadas de Valtio, como la suscripción a cambios en la tienda, y el uso de la memorización para optimizar el rendimiento de tus componentes. Al final de esta charla, tendrás una sólida comprensión de cómo Valtio puede hacer que tu gestión de estado sea más eficiente y efectiva, permitiéndote crear aplicaciones escalables y mantenibles.

Niya Panamdanam
Niya Panamdanam
10 min
15 Nov, 2023

Video Summary and Transcription

Esta es una breve presentación sobre VALTEO, un sistema de gestión de estado basado en proxies que utiliza la idea nativa de JavaScript de proxies para crear un estado observable e inmutable. El proxy rastrea los cambios en el objeto y los objetos proxy anidados, solo volviendo a renderizar el componente cuando una clave específica cambia. Hay una trampa con los proxies en Valtio - evita reasignar el proxy a un objeto completamente nuevo. Valtio se integra con Redux DevTools, lo que lo hace aún más potente y conveniente.

Available in English

1. Introducción a la gestión de estado de VALTEO

Short description:

Esta es una breve presentación sobre VALTEO, un sistema de gestión de estado basado en proxies que utiliza la idea nativa de proxies de JavaScript para crear un estado observable e inmutable. Elimina la necesidad de una configuración extensa, lo que lo hace ideal para aplicaciones React heredadas. Los proxies de JavaScript actúan como escudos alrededor de los objetos, permitiéndote cambiar lo que ves y añadir reglas y controles para proteger tu objeto. Valteo simplifica el proceso y proporciona código de plantilla para la parte de proxy, facilitando la gestión del estado en componentes de clase o componentes de JavaScript puro. La implementación de React implica importar el proxy y utilizar la mutación directa del objeto para cambiar los valores del estado.

Entonces, esta es una presentación realmente corta sobre VALTEO, que técnicamente es un estado global pero la parte realmente maravillosa de esto es que puedes tratarlo como una micro-gestión de estado, lo que significa que solo usas lo que necesitas y no tienes que cambiar todo tu paradigma. Entonces, un poco sobre mí. Mi nombre es Nia, vivo en Toronto, solía vivir en Atlanta en los Estados Unidos y ahora trabajo para una empresa que se llama Healthy y hacen telemedicina y están basados en Nueva York. Entonces, viajo por todos lados. Y trabajo como líder técnico de front-end y arquitecto.

Entonces, Valtio es más o menos cómo hemos introducido la gestión de estado a nuestra aplicación heredada también. Entonces, ¿qué es Valtio, verdad? Aquí tengo el enlace a GitHub de Valtio también, así que si estás interesado, eso es realmente genial. Pero la mejor parte de Valtio es que es un sistema de gestión de estado basado en proxies. Utiliza la idea nativa de proxies de JavaScript para crear un estado observable. Es un estado inmutable. Entonces, te permite actualizar el estado básicamente como actualizarías un objeto, pero cuando el estado cambia, todo se registra y se crean nuevos objetos de estado en lugar de modificar los existentes, ¿verdad? Y la mejor parte de esto es que en general hay una mínima plantilla. Entonces, incluso con Redux o todos los demás, como, son geniales a su manera, pero hay tanta configuración, y especialmente si estás trabajando en aplicaciones React realmente antiguas donde todavía hay muchos componentes de clase, es súper fácil. No hay muchas cosas que, como, configurar y simplemente comienza a funcionar. Pero vamos a profundizar en el concepto de proxies de JavaScript. Fue introducido en ES6, y al menos la forma en que lo he pensado, y me ha ayudado a entender es que es como un escudo alrededor de tu objeto. Protege tu objeto. Básicamente, cambia lo que ves cuando miras el objeto, las propiedades o los valores, por ejemplo, y puedes hacer que el objeto se vea diferente, añadir información extra o incluso ocultar ciertas partes. La otra parte que es realmente genial es que ahora también puedes pasar funciones de controlador y controlar lo que sucede cuando intentas hacer cosas con el objeto, como cambiar una propiedad, leer una propiedad, o llamar a una función, ¿verdad? Así que puedes añadir reglas y controles y balances a ello, por lo que protege tu objeto mientras intentas cambiarlo. Puedes leer más sobre ello aquí también, en este pequeño enlace. Así que aquí, ese mismo código, lo que quería mostrarte aquí es que he configurado mi objeto objetivo, tengo una función de controlador, y lo he configurado dentro de mi proxy, y lo que hay que notar aquí es que el mensaje dos aquí dice everyone. Normalmente, cuando haces target.message dos, obtendrías everyone como respuesta, pero como pasa por mi proxy, cuando hago proxy.message dos, en realidad voy a obtener world en lugar de everyone, porque de cómo el proxy establece aquí, la función de controlador, establece que si la propiedad es igual a message devuelve world. Así que aunque target.message dos es everyone, el proxy lo protege y dice proxy.message dos, que está tomando target aquí, devolverá world. Así que esto es más o menos la base de cómo funciona Valteo, pero toda esta plantilla aquí, ellos la han hecho mucho más simple para nosotros. Veamos cómo se ve. Bueno, antes de eso, por qué esto importa es que esto funciona con componentes de clase. Sé que con muchas cosas de Redux o incluso React query, todo el mundo está en hooks, pero si todavía estás en aplicaciones grandes heredadas o estás transfiriendo y estás tratando de manejar la deuda técnica, esta es una gran manera de tratar de encontrar un equilibrio entre los dos mientras estás en transición, pero todavía obtienes aspectos de la gestión de estado global en un componente de clase o en componentes de JavaScript puro y todavía puedes avanzar. Entonces, veamos cómo es la implementación de React. Uno, aquí puedes ver, es solo importar proxy, y Valtio ha configurado toda esa plantilla para tu parte de proxy, así que no tienes que hacer ninguno de ese trabajo. Tengo mi proxy de estado de persona aquí, y mi estado de autenticación, que tiene un proxy anidado, que es el estado de la persona del usuario, ¿verdad? Entonces, la forma en que lo mutaría o lo accedería, como está establecido aquí, es auth state.userDate.name equals Nina, ¿verdad? Eso es un

2. Seguimiento de Proxy y Re-renderizado de Componentes

Short description:

El proxy rastrea los cambios en el objeto y los objetos proxy anidados. Solo vuelve a renderizar el componente cuando cambia una clave específica. Esto elimina la necesidad de preocuparse por cómo se vuelve a renderizar todo el componente cuando cambian todas las cosas del contexto.

mutación del objeto, y eso es todo. Así es literalmente cómo cambias tu state management, tus valores de estado en tu estado. El proxy en sí rastrea los cambios, y todo el objeto, así como todos los objetos proxy anidados. Se agrupan varios cambios, y si el valor del cambio es el mismo, no vuelve a renderizar el componente. No cambia esas cosas. Solo cambiará si el valor es realmente diferente. Ahora, así es como cambias los data. Así es como lees los data. Básicamente, lees los data dentro de tus componentes usando instantáneas, y puedes usar el hook de instantánea o como se mostró anteriormente en la otra diapositiva, puedes usar la parte de instantánea de JavaScript de Valtio. Y básicamente aquí, como puedes ver en mi componente de perfil de usuario, tengo tu instantánea, AuthState.user, y mi div está usando el snap.name, que es de este objeto que puedes ver, estoy accediendo al state.name de la persona. Ahora, la parte realmente genial de esto es que Valtio realmente envuelve la instantánea para acceder al seguimiento de los cambios del proxy y solo vuelve a renderizar tu componente cuando cambia una clave específica. Así que no importará si cambió el estado de AuthState o a menos que yo específicamente lo pida para que lo mire. No importará si cambió el rol de la persona incluso, a menos que específicamente la parte de snap.name esté cambiando. Esa es la clave. Lo siento, en realidad importará, que el rol cambió, porque estamos mirando la instantánea aquí diciendo AuthState.user. Así que básicamente la parte del usuario aquí en todos los cambios, es cuando este componente entero se vuelve a renderizar. De lo contrario, si tenemos otra información en AuthState, como no sé, tokens o algo más, no lo mirará a menos que específicamente digas míralo. Esto significa que no tienes que preocuparte por cómo se vuelve a renderizar todo tu componente cuando cambian todas las cosas del contexto. Ese es uno de los problemas con useContext, que de alguna manera se va

3. Problema con Proxy e Integración de Redux DevTools

Short description:

Existe un problema al trabajar con proxies en Valtio. Evita reasignar el proxy a un objeto completamente nuevo. En su lugar, utiliza la función de suscripción para rastrear los cambios. Reasignar el estado a un nuevo objeto romperá la suscripción. Valtio también se integra con Redux DevTools, lo que lo hace aún más potente y conveniente. Consulta la documentación de Valtio y el repositorio de GitHub para obtener más información y tutoriales.

contigo. Ahora, hay un problema que debemos tener en cuenta. No reasignes tu proxy a un objeto completamente nuevo. Así que Valtio también tiene una función de suscripción que te permite suscribirte a los cambios en el proxy. Por lo general, para la mayoría de los componentes, puedes utilizar la instantánea para disparar el componente para volver a renderizar. En algunos casos raros, quieres mirar el cambio del proxy directamente, como en la mutación directa de ese proxy. Entonces puedes usar la suscripción. Aquí, puedes ver que tengo mi estado de proxy, y tiene proxy username igual a Timo, y me estoy suscribiendo a él, pero entonces hay este nuevo objeto. Básicamente he dicho que el estado se redefine como un nuevo objeto ahora, que es username Nina. He eliminado completamente el proxy aquí, y al asignar el estado a un objeto completamente nuevo, la suscripción no funcionará en absoluto. Así que en su lugar, deberías hacer una mutación directa aquí, state.user.name. Entonces el suscriptor realmente podrá rastrear ese cambio de proxy y decir, hey, tu estado se actualizó y cambia todo lo demás que sea necesario en consecuencia. Así que una cosa más genial antes de irme. Funciona con Redux DevTools, lo cual encuentro realmente impresionante. Esto es literalmente el código básico para eso. Eso es todo. Solo configuras tu estado. Luego lo configuras con DevTools. Puedes importar DevTools desde Valtier Utils y luego configurarlo para que sea el nombre del estado y habilitar true, y entonces es Redux DevTools. Y ahora puedes usar state management en cualquier aplicación que quieras sin añadir nada extra. Estos son algunos enlaces y tutoriales realmente geniales incluso sobre Valtier y cómo usarlo. Sus documentos y su perfil de GitHub aquí o su repositorio de GitHub es realmente, realmente genial. Recomiendo mucho sus documentos, realmente me encantan. Eso es todo lo que tengo para ustedes. Gracias.

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

A Guide to React Rendering Behavior
React Advanced Conference 2022React Advanced Conference 2022
25 min
A Guide to React Rendering Behavior
Top Content
React is a library for "rendering" UI from components, but many users find themselves confused about how React rendering actually works. What do terms like "rendering", "reconciliation", "Fibers", and "committing" actually mean? When do renders happen? How does Context affect rendering, and how do libraries like Redux cause updates? In this talk, we'll clear up the confusion and provide a solid foundation for understanding when, why, and how React renders. We'll look at: - What "rendering" actually is - How React queues renders and the standard rendering behavior - How keys and component types are used in rendering - Techniques for optimizing render performance - How context usage affects rendering behavior| - How external libraries tie into React rendering
Building Better Websites with Remix
React Summit Remote Edition 2021React Summit Remote Edition 2021
33 min
Building Better Websites with Remix
Top Content
Remix is a new web framework from the creators of React Router that helps you build better, faster websites through a solid understanding of web fundamentals. Remix takes care of the heavy lifting like server rendering, code splitting, prefetching, and navigation and leaves you with the fun part: building something awesome!
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.
React Compiler - Understanding Idiomatic React (React Forget)
React Advanced Conference 2023React Advanced Conference 2023
33 min
React Compiler - Understanding Idiomatic React (React Forget)
Top Content
React provides a contract to developers- uphold certain rules, and React can efficiently and correctly update the UI. In this talk we'll explore these rules in depth, understanding the reasoning behind them and how they unlock new directions such as automatic memoization. 
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.
Routing in React 18 and Beyond
React Summit 2022React Summit 2022
20 min
Routing in React 18 and Beyond
Top Content
Concurrent React and Server Components are changing the way we think about routing, rendering, and fetching in web applications. Next.js recently shared part of its vision to help developers adopt these new React features and take advantage of the benefits they unlock.In this talk, we’ll explore the past, present and future of routing in front-end applications and discuss how new features in React and Next.js can help us architect more performant and feature-rich applications.

Workshops on related topic

React Performance Debugging Masterclass
React Summit 2023React Summit 2023
170 min
React Performance Debugging Masterclass
Top Content
Featured WorkshopFree
Ivan Akulov
Ivan Akulov
Ivan’s first attempts at performance debugging were chaotic. He would see a slow interaction, try a random optimization, see that it didn't help, and keep trying other optimizations until he found the right one (or gave up).
Back then, Ivan didn’t know how to use performance devtools well. He would do a recording in Chrome DevTools or React Profiler, poke around it, try clicking random things, and then close it in frustration a few minutes later. Now, Ivan knows exactly where and what to look for. And in this workshop, Ivan will teach you that too.
Here’s how this is going to work. We’ll take a slow app → debug it (using tools like Chrome DevTools, React Profiler, and why-did-you-render) → pinpoint the bottleneck → and then repeat, several times more. We won’t talk about the solutions (in 90% of the cases, it’s just the ol’ regular useMemo() or memo()). But we’ll talk about everything that comes before – and learn how to analyze any React performance problem, step by step.
(Note: This workshop is best suited for engineers who are already familiar with how useMemo() and memo() work – but want to get better at using the performance tools around React. Also, we’ll be covering interaction performance, not load speed, so you won’t hear a word about Lighthouse 🤐)
Concurrent Rendering Adventures in React 18
React Advanced Conference 2021React Advanced Conference 2021
132 min
Concurrent Rendering Adventures in React 18
Top Content
Featured WorkshopFree
Maurice de Beijer
Maurice de Beijer
With the release of React 18 we finally get the long awaited concurrent rendering. But how is that going to affect your application? What are the benefits of concurrent rendering in React? What do you need to do to switch to concurrent rendering when you upgrade to React 18? And what if you don’t want or can’t use concurrent rendering yet?

There are some behavior changes you need to be aware of! In this workshop we will cover all of those subjects and more.

Join me with your laptop in this interactive workshop. You will see how easy it is to switch to concurrent rendering in your React application. You will learn all about concurrent rendering, SuspenseList, the startTransition API and more.
React Hooks Tips Only the Pros Know
React Summit Remote Edition 2021React Summit Remote Edition 2021
177 min
React Hooks Tips Only the Pros Know
Top Content
Featured Workshop
Maurice de Beijer
Maurice de Beijer
The addition of the hooks API to React was quite a major change. Before hooks most components had to be class based. Now, with hooks, these are often much simpler functional components. Hooks can be really simple to use. Almost deceptively simple. Because there are still plenty of ways you can mess up with hooks. And it often turns out there are many ways where you can improve your components a better understanding of how each React hook can be used.You will learn all about the pros and cons of the various hooks. You will learn when to use useState() versus useReducer(). We will look at using useContext() efficiently. You will see when to use useLayoutEffect() and when useEffect() is better.
React, TypeScript, and TDD
React Advanced Conference 2021React Advanced Conference 2021
174 min
React, TypeScript, and TDD
Top Content
Featured WorkshopFree
Paul Everitt
Paul Everitt
ReactJS is wildly popular and thus wildly supported. TypeScript is increasingly popular, and thus increasingly supported.

The two together? Not as much. Given that they both change quickly, it's hard to find accurate learning materials.

React+TypeScript, with JetBrains IDEs? That three-part combination is the topic of this series. We'll show a little about a lot. Meaning, the key steps to getting productive, in the IDE, for React projects using TypeScript. Along the way we'll show test-driven development and emphasize tips-and-tricks in the IDE.
Web3 Workshop - Building Your First Dapp
React Advanced Conference 2021React Advanced Conference 2021
145 min
Web3 Workshop - Building Your First Dapp
Top Content
Featured WorkshopFree
Nader Dabit
Nader Dabit
In this workshop, you'll learn how to build your first full stack dapp on the Ethereum blockchain, reading and writing data to the network, and connecting a front end application to the contract you've deployed. By the end of the workshop, you'll understand how to set up a full stack development environment, run a local node, and interact with any smart contract using React, HardHat, and Ethers.js.
Designing Effective Tests With React Testing Library
React Summit 2023React Summit 2023
151 min
Designing Effective Tests With React Testing Library
Top Content
Featured Workshop
Josh Justice
Josh Justice
React Testing Library is a great framework for React component tests because there are a lot of questions it answers for you, so you don’t need to worry about those questions. But that doesn’t mean testing is easy. There are still a lot of questions you have to figure out for yourself: How many component tests should you write vs end-to-end tests or lower-level unit tests? How can you test a certain line of code that is tricky to test? And what in the world are you supposed to do about that persistent act() warning?
In this three-hour workshop we’ll introduce React Testing Library along with a mental model for how to think about designing your component tests. This mental model will help you see how to test each bit of logic, whether or not to mock dependencies, and will help improve the design of your components. You’ll walk away with the tools, techniques, and principles you need to implement low-cost, high-value component tests.
Table of contents- The different kinds of React application tests, and where component tests fit in- A mental model for thinking about the inputs and outputs of the components you test- Options for selecting DOM elements to verify and interact with them- The value of mocks and why they shouldn’t be avoided- The challenges with asynchrony in RTL tests and how to handle them
Prerequisites- Familiarity with building applications with React- Basic experience writing automated tests with Jest or another unit testing framework- You do not need any experience with React Testing Library- Machine setup: Node LTS, Yarn