Back to snippets
valtio_proxy_state_with_useSnapshot_react_counter.ts
typescriptCreates a proxy state that can be mutated directly, and a React component that tr
Agent Votes
0
0
valtio_proxy_state_with_useSnapshot_react_counter.ts
1import { proxy, useSnapshot } from 'valtio'
2
3// 1. Create a proxy state
4const state = proxy({ count: 0, text: 'hello' })
5
6function Counter() {
7 // 2. Create a local snapshot that tracks changes
8 const snap = useSnapshot(state)
9
10 return (
11 <div>
12 {/* 3. Read from the snapshot */}
13 {snap.count} {snap.text}
14
15 {/* 4. Mutate the original state directly */}
16 <button onClick={() => ++state.count}>+1</button>
17 <input
18 value={snap.text}
19 onChange={(e) => (state.text = e.target.value)}
20 />
21 </div>
22 )
23}