Valtio is a minimalistic, proxy-based state management library primarily designed for React, but due to its core JavaScript implementation, it can be used with other frameworks as well. It leverages JavaScript Proxies to enable direct mutation of state objects while ensuring reactive updates in components that consume that state.
Key Concepts:
1. `proxy(initialState)`: This is the core function to create your state. It takes an initial JavaScript object and returns a mutable proxy object around it. You can directly modify properties of this proxy object, just like a regular JavaScript object (`store.count++`). Valtio intercepts these mutations.
2. `useSnapshot(proxyState)`: In React components, you use `useSnapshot` to access a read-only snapshot of the proxy state created by `proxy()`. When the underlying proxy state changes, `useSnapshot` detects these changes and triggers a re-render of the component. The snapshot ensures that components only re-render when the specific parts of the state they actually use are modified, optimizing performance and preventing unnecessary re-renders.
How it Works:
Valtio's elegance lies in its use of JavaScript Proxies. When you create a state object with `proxy()`, Valtio wraps it in a Proxy. When a component calls `useSnapshot(store)`, Valtio creates an immutable snapshot of the current `store` state. More importantly, it observes which properties of the `store` are accessed during the component's render. If any of those observed properties are later modified via the `store` proxy, Valtio knows exactly which components need to be re-rendered.
Features and Benefits:
* Simple API: Very few core functions to learn (`proxy`, `useSnapshot`), making it easy to get started.
* Mutable State: Allows direct modification of state objects, which often feels more natural and simplifies state updates compared to strict immutable patterns (like Redux).
* Automatic Re-renders: Components automatically re-render when relevant state changes, without manual subscriptions or complex memoization setup.
* Fine-grained Reactivity: Only components that use the changed parts of the state re-render, leading to efficient updates.
* TypeScript Friendly: Provides excellent type inference and support out of the box.
* Lightweight: Small bundle size, contributing to faster application load times.
* No Boilerplate: Eliminates the need for actions, reducers, or complex setup for many common state management scenarios.
Valtio provides a highly intuitive and efficient way to manage global or local component state, making it a popular choice for developers looking for a simpler, yet powerful alternative to more verbose state management solutions.
Example Code
import React from 'react';
import { proxy, useSnapshot } from 'valtio';
// 1. Define your global state using `proxy`
// This object is mutable and can be directly modified.
const appStore = proxy({
count: 0,
message: "Hello Valtio!",
items: ['apple', 'banana', 'orange']
});
// 2. Component to display the current count and message
function CounterDisplay() {
// Use `useSnapshot` to get a read-only snapshot of the store.
// This component will re-render whenever `appStore.count` or `appStore.message` changes
// because those properties are accessed here.
const snap = useSnapshot(appStore);
return (
<div style={{ marginBottom: '20px' }}>
<h2>Count: {snap.count}</h2>
<p>Message: "{snap.message}"</p>
</div>
);
}
// 3. Component to display the list of items
function ItemList() {
const snap = useSnapshot(appStore);
return (
<div style={{ marginBottom: '20px' }}>
<h3>Items:</h3>
<ul>
{snap.items.map((item, index) => (
<li key={index}>{item}</li>
))}
</ul>
</div>
);
}
// 4. Component to control the count and message
function Controls() {
const [newItem, setNewItem] = React.useState('');
const handleAddItem = () => {
if (newItem.trim()) {
// Directly mutate the proxy state to add an item
appStore.items.push(newItem.trim());
setNewItem('');
}
};
return (
<div style={{ display: 'flex', flexDirection: 'column', gap: '10px' }}>
<div style={{ display: 'flex', gap: '10px', justifyContent: 'center' }}>
<button onClick={() => appStore.count++}>Increment Count</button>
<button onClick={() => appStore.count--}>Decrement Count</button>
</div>
<button onClick={() => appStore.message = (appStore.message === "Hello Valtio!" ? "Valtio is awesome!" : "Hello Valtio!")}>
Toggle Message
</button>
<div style={{ display: 'flex', gap: '5px', justifyContent: 'center' }}>
<input
type="text"
value={newItem}
onChange={(e) => setNewItem(e.target.value)}
placeholder="Add new item"
style={{ padding: '8px', borderRadius: '4px', border: '1px solid #ccc' }}
/>
<button onClick={handleAddItem}>Add Item</button>
</div>
</div>
);
}
// 5. Main App component
export default function App() {
return (
<div style={{
fontFamily: 'Arial, sans-serif',
textAlign: 'center',
maxWidth: '500px',
margin: '50px auto',
padding: '30px',
border: '1px solid #e0e0e0',
borderRadius: '10px',
boxShadow: '0 4px 12px rgba(0,0,0,0.05)',
backgroundColor: '#fff'
}}>
<h1>Valtio State Management Example</h1>
<CounterDisplay />
<ItemList />
<Controls />
</div>
);
}








Valtio