React State Management with Valtio

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.

Rate this content
Bookmark
Watch video on a separate page
Video Summary and Transcription
Valtio is a state management system that utilizes JavaScript's native proxies to create an observable and immutable state. It streamlines state management in legacy React applications by eliminating the need for extensive setup. The Valtio proxy acts as a shield around objects, allowing direct object mutation while maintaining performance efficiency. One of the key features of Valtio is the subscribe function, which tracks state changes and ensures components re-render only when necessary. This prevents unnecessary re-renders and optimizes performance. JavaScript proxies are central to Valtio's functionality, enabling it to manage state changes effectively. Valtio's compatibility with Redux DevTools provides a powerful tool for developers to visualize and track state changes during development. The Valtio documentation and GitHub repository offer valuable resources for learning more about its features and implementation.

This talk has been presented at React Summit US 2023, check out the latest edition of this React Conference.

FAQ

Valtio is a proxy-based state management system that uses JavaScript's native proxies to create observable and immutable state. It allows you to update the state like an object, but logs changes and creates new state objects instead of modifying existing ones.

JavaScript proxies, introduced in ES6, act as a shield around objects, allowing you to control interactions with object properties. Valtio uses these proxies to manage state changes and make the state observable and immutable.

Yes, Valtio works well with class components in React, making it a good choice for managing state in legacy applications or during transitions from older codebases.

State values in Valtio are changed by directly mutating the proxy state object. For example, authState.userDate.name = 'Nina' directly updates the state value.

Yes, Valtio supports Redux DevTools. You can set it up by importing DevTools from 'valtio/utils' and configuring it with your state, enabling true for integration.

Valtio's documentation and GitHub repository are highly recommended for learning more about its features and usage. They provide tutorials and detailed information on implementing Valtio in your projects.

The presenter is Nia, who works as a front-end tech lead and architect for a telehealth company called Healthy based in New York. She has experience living in Toronto and Atlanta.

Avoid reassigning your proxy to a whole new object, as this will break the subscription to state changes. Instead, perform direct mutations on the proxy state object.

The snapshot function in Valtio is used to read state data within components. It tracks proxy changes and re-renders components only when the specific state keys they depend on change.

Valtio has minimal boilerplate compared to systems like Redux, making it easier to use, especially in older React applications with class components. It leverages JavaScript proxies for state management, reducing setup complexity.

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.

Niya Panamdanam
Niya Panamdanam
10 min
15 Nov, 2023

Comments

Sign in or register to post your comment.

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 2022React Advanced 2022
25 min
A Guide to React Rendering Behavior
Top Content
This transcription provides a brief guide to React rendering behavior. It explains the process of rendering, comparing new and old elements, and the importance of pure rendering without side effects. It also covers topics such as batching and double rendering, optimizing rendering and using context and Redux in React. Overall, it offers valuable insights for developers looking to understand and optimize 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 web framework built on React Router that focuses on web fundamentals, accessibility, performance, and flexibility. It delivers real HTML and SEO benefits, and allows for automatic updating of meta tags and styles. It provides features like login functionality, session management, and error handling. Remix is a server-rendered framework that can enhance sites with JavaScript but doesn't require it for basic functionality. It aims to create quality HTML-driven documents and is flexible for use with different web technologies and stacks.
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
State management is not limited to complex applications and transitioning to a store offers significant benefits. Pinia is a centralized state management solution compatible with Vue 2 and Vue 3, providing advanced devtools support and extensibility with plugins. The core API of Pinia is similar to Vuex, but with a less verbose version of stores and powerful plugins. Pinia allows for easy state inspection, error handling, and testing. It is recommended to create one file per store for better organization and Pinia offers a more efficient performance compared to V-rex.
React Compiler - Understanding Idiomatic React (React Forget)
React Advanced 2023React Advanced 2023
33 min
React Compiler - Understanding Idiomatic React (React Forget)
Top Content
Watch video: React Compiler - Understanding Idiomatic React (React Forget)
Joe Savona
Mofei Zhang
2 authors
The Talk discusses React Forget, a compiler built at Meta that aims to optimize client-side React development. It explores the use of memoization to improve performance and the vision of Forget to automatically determine dependencies at build time. Forget is named with an F-word pun and has the potential to optimize server builds and enable dead code elimination. The team plans to make Forget open-source and is focused on ensuring its quality before release.
Using useEffect Effectively
React Advanced 2022React Advanced 2022
30 min
Using useEffect Effectively
Top Content
Today's Talk explores the use of the useEffect hook in React development, covering topics such as fetching data, handling race conditions and cleanup, and optimizing performance. It also discusses the correct use of useEffect in React 18, the distinction between Activity Effects and Action Effects, and the potential misuse of useEffect. The Talk highlights the benefits of using useQuery or SWR for data fetching, the problems with using useEffect for initializing global singletons, and the use of state machines for handling effects. The speaker also recommends exploring the beta React docs and using tools like the stately.ai editor for visualizing state machines.
Routing in React 18 and Beyond
React Summit 2022React Summit 2022
20 min
Routing in React 18 and Beyond
Top Content
Routing in React 18 brings a native app-like user experience and allows applications to transition between different environments. React Router and Next.js have different approaches to routing, with React Router using component-based routing and Next.js using file system-based routing. React server components provide the primitives to address the disadvantages of multipage applications while maintaining the same user experience. Improving navigation and routing in React involves including loading UI, pre-rendering parts of the screen, and using server components for more performant experiences. Next.js and Remix are moving towards a converging solution by combining component-based routing with file system routing.

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 2021React Advanced 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 2021React Advanced 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 2021React Advanced 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