React State Management with Valtio

Rate this content
Bookmark

In this talk, we will explore how Valtio can simplify your React state management by providing a minimalist and performant solution. We will cover the basics of Valtio, including how to create and update a store and how to access and modify the store from your components. We will also dive into some advanced Valtio features, such as subscribing to changes in the store, andusing memoization to optimize your components' performanc. By the end of this talk, you will have a solid understanding of how Valtio can make your state management more efficient and effective, allowing you to create scalable and maintainable applications.

10 min
15 Nov, 2023

AI Generated Video Summary

This is a short presentation on VALTEO, a proxy-based state management system that uses JavaScript's native idea of proxies to create observable and immutable state. The proxy tracks changes to the object and nested proxy objects, only re-rendering the component when a specific key changes. There is a gotcha with proxies in Valtio - avoid reassigning the proxy to a whole new object. Valtio integrates with Redux DevTools, making it even more powerful and convenient.

1. Introduction to VALTEO State Management

Short description:

This is a short presentation on VALTEO, a proxy-based state management system that uses JavaScript's native idea of proxies to create observable and immutable state. It eliminates the need for extensive setup, making it ideal for legacy React applications. JavaScript proxies act as shields around objects, allowing you to change what you see and add rules and checks to protect your object. Valteo simplifies the process and provides boilerplate code for the proxy part, making state management in class components or vanilla JavaScript components easier. The React implementation involves importing the proxy and using direct object mutation to change state values.

So, this is a really short presentation on VALTEO, which is technically a global state but the really wonderful part about it is you can actually treat it as a micro-state management, which sort of means that you only use what you need and you don't have to change your whole paradigm.

So, a little about me. My name is Nia, I live in Toronto, I used to live in Atlanta in the US and now I work for a company that's called Healthy and they do telehealth and they're based out of New York. So, travel all over the place. And I work as a front-end tech lead and architect.

So, Valtio is sort of how we've introduced state management to our legacy application as well. So, what is Valtio, right? Right here I've got the GitHub link to Valtio as well, so if you're ever interested, that's really cool. But the best part about Valtio is it's a proxy-based state management system. It uses JavaScript's native idea of proxies to create observable state. It's immutable state. So, it lets you update the state basically how you'd update an object, but when the state changes, everything is logged and new state objects are created rather than modifying existing ones, right? And the best part about it is overall minimal boilerplate.

So, even with Redux or all the other ones, like, they are great in their own ways, but there's so much setup, and especially if you're working in really old React applications where there's still a lot of class components, it's super easy. There's not a lot of stuff to, like, configure and it just starts working. But let's dig in to the concept of JavaScript proxies. It was actually introduced in ES6, and at least the way I've thought about it, and it sort of helped me understand is it's sort of a shield around your object. It sort of protects your object. Basically, it changes what you see when you look at the object, properties or values, for example, and you can make the object look different, add extra information or even hide certain parts. The other part of it that's really cool is now you can also pass in handler functions and controls what happens when you try to do things with the object, like changing a property, reading a property, or calling a function, right? So you can add rules and checks and balances to it, so it protects your object as you try to change it.

So here, that same code, the thing I just wanted to show you here is I've set up my object target, I've got a handler function, and I've set it up inside my proxy, and the thing to note here is message two here says everyone. Usually, when you do target.message two, you'd get everyone as a response, but because it goes through my proxy, when I do proxy.message two, I'm actually gonna get world rather than everyone, because of how the proxy states right here, the handler function, it states if the prop equals message return world. So even though target.message two is everyone, the proxy protects it and says proxy.message two, which is taking target here, will return world. So this is sort of the foundation of how Valteo works, but this whole boilerplate here, they've actually made it much simpler for us. Let's look at how it looks. Well, before that, why this matters is this works with class components. I know with a lot of Redux stuff or React query even, everyone is on hooks, but if you're still in legacy large applications or you're transferring over and you're trying to manage tech debt, this is a great way of trying to find balance between the two while you're in transition, but you still get aspects of global state management in a class component or in vanilla JavaScript components and still able to move forward. So let's just look at how the React implementation is. One, here you can see, it's just import proxy, and Valtio is actually set up all that boilerplate for your proxy part, so you don't have to do any of that work. I've got my person state proxy here, and my auth state, which has a nested proxy, which is user person state, right? So, the way I would mutate it or access it, as it's set here, is auth state.userDate.name equals Nina, right? That's a direct object mutation, and that's it. That is literally how you change your state management, your state values in your state.

2. Proxy Tracking and Component Re-rendering

Short description:

The proxy tracks changes to the object and nested proxy objects. It only re-renders the component when a specific key changes. This eliminates the need to worry about how the whole component re-renders when all the context stuff changes.

That is literally how you change your state management, your state values in your state. The proxy itself tracks the changes, and all of the object, as well as all the nested proxy objects. Multiple changes are batched, and if the value of the change is the same, it doesn't rerender the component. It doesn't change those things. It will only change if the value is actually different.

Now, that's how you change the data. This is how you read the data. Basically, you read the data within your components using snapshots, and you can use the snapshot hook or like previously shown in the other slide, you can use the vanilla JavaScript snapshot part of Valtio. And basically here, as you can see in my user profile component, I've got your snapshot, AuthState.user, and my div is using the snap.name, which is from this object you can see, I'm tapping into the person's state.name.

Now, the really cool part about this is Valtio actually wraps the snapshot to access the tracking of the proxy changes, and it only re-renders your component when the specific key changes. So it won't matter if AuthState status changed or unless I specifically asked for it to look at that. It won't matter if the role changed for the person even, unless specifically the snap.name part is changing. That's the key. Sorry, actually it will matter, that role changed, because we're looking at snapshot here saying AuthState.user. So basically the user part here at all changes, that's when this whole component re-renders. Otherwise, if we have other information in AuthState, like I don't know, tokens or something else, it won't look at it unless you specifically say look at it. This means you don't have to worry about how your whole component re-renders when all the context stuff changes. That's one of the problems with useContext, that sort of goes away with you.

3. Gotcha with Proxy and Redux DevTools Integration

Short description:

There is a gotcha when working with proxies in Valtio. Avoid reassigning the proxy to a whole new object. Instead, use the subscribe function to track changes. Reassigning the state to a new object will break the subscription. Valtio also integrates with Redux DevTools, making it even more powerful and convenient. Check out the Valtio documentation and GitHub repository for more information and tutorials.

Now, there is a gotcha that we should watch out for. Don't reassign your proxy to a whole new object. So Valtio also has a subscribe function that lets you subscribe to the changes on proxy. Usually for most components, you can use the snapshot to trigger the component to re-render. In some rare cases, you want to look at the proxy changed directly, as in the direct mutation of that proxy. So then you can use subscribe.

Here, you can see I've got my proxy state, and it's got proxy username equals Timo, and I'm subscribing to it, but then there's this new object. I've basically said state is redefined as a new object now, which is username Nina. I've completely removed the proxy here, and by assigning state to a whole new object, the subscribe won't work at all. So instead, you should just do a direct mutation right here, state.user.name. Then the subscriber will actually be able to track that proxy change and say, hey, your state updated and change everything else that is necessary accordingly.

So one more cool thing before I'm off. It works with Redux DevTools, which I find really awesome. This is literally the boilerplate for that. That's it. You just set up your state. Then you set it up with DevTools. You can import DevTools from the Valtier Utils and then set it up to be the name of the state and enable true, and it's then Redux DevTools. And you get to now use state management in whatever application you want without any other extra things to add to it. These are some really cool links and tutorials even on Valtier and how to use it. Their docs and their GitHub profile here or their GitHub repo is really, really cool. Highly recommend their docs, really love it. That's everything I've got for you guys.

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

React Advanced Conference 2022React Advanced Conference 2022
25 min
A Guide to React Rendering Behavior
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
React Summit Remote Edition 2021React Summit Remote Edition 2021
33 min
Building Better Websites with Remix
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!
Vue.js London Live 2021Vue.js London Live 2021
34 min
Everything Beyond State Management in Stores with Pinia
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 Advanced Conference 2022React Advanced Conference 2022
30 min
Using useEffect Effectively
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 Summit 2022React Summit 2022
20 min
Routing in React 18 and Beyond
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 Summit 2023React Summit 2023
170 min
React Performance Debugging Masterclass
Featured WorkshopFree
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 🤐)
React Advanced Conference 2021React Advanced Conference 2021
132 min
Concurrent Rendering Adventures in React 18
Featured WorkshopFree
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 Summit Remote Edition 2021React Summit Remote Edition 2021
177 min
React Hooks Tips Only the Pros Know
Featured Workshop
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 Advanced Conference 2021React Advanced Conference 2021
174 min
React, TypeScript, and TDD
Featured WorkshopFree
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.
React Advanced Conference 2021React Advanced Conference 2021
145 min
Web3 Workshop - Building Your First Dapp
Featured WorkshopFree
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.
React Summit 2023React Summit 2023
151 min
Designing Effective Tests With React Testing Library
Featured Workshop
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