React State Management with Valtio: A Proxy-Based Approach
Deciding on the right state management tool is one of the most crucial decisions before developing a web application. There are many tools and techniques to manage application states, but people tend to over-engineer selecting tools that are way too complex and introduce boilerplate codes. People started moving towards simple or lightweight state management tools like Zustand, Jotai, Recoil, Context API to address this issue.
In this article, let's look into another simple state management tool called Valtio, a Proxy-based tool that aims to address the issues brought by some famous state management tools like Redux.
What is Valtio
Valtio is a small tool for managing state in react applications. Valtio is developed by the same developers of Jotia and Zustand. Valtio uses a Proxy pattern underneath, enabling us to subscribe to specific parts of your application state. It avoids traditional selecting or diffing techniques to subscribe to the application state.
What makes it unique
Valtio is based on state mutation style. So you don't need to use traditional methods like selectors and diffing to identify and re-render the state's components. Hookstate is one of the first libraries that adopted the Proxy design pattern, which helps to solve the repeating issues in modern applications such as mutating states and listening or subscribing to the application state. Proxies have two significant rules.
- You should control the Javascript object wrapped with a proxy
- You should provide the functionality to access the objects
Unlike Redux or Zustand, the proxy pattern won't require unique action to be fired, and it's easy to subscribe to values in the store. Let's look at a proxy and see how it works.
A Proxy
object wraps another object and intercepts operations, like reading/writing properties and others, optionally handling them independently or transparently, allowing the object to handle them. A proxy takes two parameters.
target
– is an object to wrap, can be anything, including functions.handler
– proxy configuration: an object with "traps," methods that intercept operations (typically get or set).
let proxy = new Proxy(target, handler)
If a proxy object doesn't have a handler function, it would directly forward the target object. You can provide additional features to a proxy through the handlers, which will allow reading (get
), writing (set
), deleting (deleteProperty
) a property (even a non-existing one). Now let's look into an example with a proper target and a handler function.
let state = {
'Pokemon': 'Pickachu',
'Power': 'Fire'
};
state = new Proxy(state, {
get(target, phrase) { // intercept reading a property from state
if (phrase in target) { // if we have it in the state
return target[phrase]; // return the translation
}
else {
// otherwise, return the non-translated phrase
return phrase;
}
}
});
// Look up arbitrary phrases in the state!
// At worst, they're not translated.
alert(state['Pokemon']); // Pickachu
alert(state['Welcome to Pokemon World']); // Welcome to Pokemon World (no translation)
Valtio also introduces a unique feature called 'scoped state' which optimizes the rerendering of frequently changing deeply nested states to the extreme.
Valtio compared with Zustand, Jotai
Even though the same creators created all these libraries, there are several maturity, popularity, and technical differences.
Zustand uses the same pattern as Redux, which is the Flux pattern. But unlike Redux, Zustand has fewer boilprates. Jotai uses atomic patterns similar to the React state and stores the state inside the React Tree. Jotai has Atoms that will keep the application state, and the components can subscribe to these independent atoms.
Valtio uses the proxy pattern. The proxy pattern won't require unique action to be fired, just like Redux or Zustand, and it will subscribe to values in the store. Valtio looks magical, and it just works with less code and with plain JavaScript, and Valtio is unopinionated.
Get started with Valtio.
In this section, let's create a small pokemon application with valtio, covering the basic usage of valtio.
Step 01: Installation
We will be using React with TypeScript using create-react-app and install other necessary libraries along with it.
npx create-react-app valtio-pokemon --template typescript
yarn add semantic-ui-react semantic-ui-css valtio
After installing the dependencies, let's move towards creating the store of the application.
Step 02: Creating the store
First, let's create the interface for the store object and wrap the store object with the proxy wrapper from valtio.
Notice that we have added the added functions which can mutate the store data in the proxy object. We have used some common functions to update and delete pokemon data in a separate util.ts file.
Step 03: Subscribing and using store
Unlike Redux or Zustand, or Jotail, With Valtio, you have to wrap the application with a provider Higher-order component. This means you can directly import the proxy object from the store and use its data and function to mutate the state. First, let's create a Form component.
Notice that we have used a hook called useSnapshot to wrap our application state. The API method is specially used to optimize the renders that take place with react. With Valtio, it is advised to read from snapshots, mutate the source. Next, let create a List component where it would subscribe to the pokemon array.
Step o4: Playing around with Redux dev tools
You can use Redux DevTools Extension to observe the state of your store with just a couple of additional configurations. First, you need to import the DevTools method from Valtio's util API.
import { devtools } from 'valtio/utils'
const state = proxy({ isEditing: fasle, pokemons: [],.....})
const unsub = devtools(state, 'pokemon state')
You can find the complete code through the GitHub repo and working demo through this link.
Conclusion
Valtio looks to be one of the simplest state management tools out there. The power of proxies in React and JavaScript makes it easy to manage the state of the front-end application. With additional capabilities like Redux devtools and persisting functionalities, Valtio looks to be a complete package and deserves more attention in the web development community. For more information, make sure you go through the documentation of Valtio. At last, thank you for taking the time to read this. I would like to see your questions and comments below.
Cheers!