Creating and Using Valtio State
You'll learn how to create proxy-based state with proxy() and read it in React components with useSnapshot() for automatic re-renders.
The Core Idea
Valtio lets you create state objects that feel like regular JavaScript objects—you can mutate them directly! Under the hood, Valtio wraps your state in a proxy that tracks what changes. In your components, you use useSnapshot() to get a read-only version of that state. Valtio automatically re-renders your component when the specific properties you actually use change. No selectors needed—just read what you need.
Creating State with proxy()
To create Valtio state, import proxy and wrap your state object:
import { proxy } from 'valtio';
const state = proxy({
count: 0,
user: { name: 'Alice' }
});
That's it! state is now reactive. You can mutate it anywhere:
state.count++; // Just mutate it!
state.user.name = 'Bob'; // Nested objects work too
Reading State with useSnapshot()
In your React component, use useSnapshot() to read the state:
import { useSnapshot } from 'valtio';
function Counter() {
const snap = useSnapshot(state);
return (
<div>
<p>Count: {snap.count}</p>
<button onClick={() => state.count++}>Increment</button>
</div>
);
}
Notice: you read from snap but mutate the original state. The snapshot is read-only; mutations happen on the proxy object. Valtio tracks which properties you accessed in snap and only re-renders when those change.
Key Takeaway: Use proxy() to create mutable state outside components, and useSnapshot() inside components to get automatic, fine-grained re-renders based on what you actually read.