Valtio Examples
This section provides practical examples to help you get started with Valtio.
Official Examples
The Valtio repository includes several example projects that demonstrate various features and use cases. You can explore them on GitHub or open them directly in StackBlitz.
- Starter: A minimal setup to get you started quickly.
- Counter: A simple counter demonstrating basic state mutation and consumption.
- TodoMVC: A classic TodoMVC implementation.
- Todo with proxyMap: Demonstrates the
proxyMap
utility for managing collections. - Editor with History: Shows how to implement undo/redo functionality with the
valtio-history
package.
Starter Project Code
Here is the complete code for the starter example. It showcases the fundamental concepts of creating a proxy, mutating it, and using its snapshot in a React component.
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { proxy, useSnapshot } from 'valtio'
import banner from './assets/banner.svg'
// 1. Create a proxy state object
const state = proxy({ count: 0 })
// 2. Create a component that uses the state
const Counter = () => {
// 3. Use the snapshot for reading in render
const snap = useSnapshot(state)
return (
<>
<span className="text-3xl">{snap.count}</span>
<button
className="bg-sky-400 font-bold py-2 px-4 rounded"
// 4. Mutate the original proxy in callbacks
onClick={() => ++state.count}
>
+1
</button>
</>
)
}
function App() {
return (
<div className="grid place-items-center gap-6">
<a href="https://valtio.dev/" target="_blank" rel="noreferrer">
<img
src={banner}
alt="Valtio banner"
className="w-96"
style={{
filter: 'drop-shadow(0 0 2em #b2ebf2)',
}}
/>
</a>
<h1 className="text-5xl font-bold">Valtio Starter</h1>
<Counter />
</div>
)
}
createRoot(document.getElementById('root')!).render(
<StrictMode>
<App />
</StrictMode>,
)