pmndrs / valtio
- пятница, 20 ноября 2020 г. в 00:31:41
TypeScript
💊 Valtio makes proxy-state simple
npm i valtio
makes proxy-state simple
import { proxy, useProxy } from 'valtio'
const state = proxy({ count: 0, text: 'hello' })
setInterval(() => {
++state.count
}, 1000)
useProxy
function Counter() {
const snapshot = useProxy(state)
// Rule of thumb: read from snapshots, mutate the source
// The component renders when the snapshot-reads change
return (
<div>
{snapshot.count}
<button onClick={() => ++state.count}>+1</button>
</div>
)
}
import { subscribe } from 'valtio'
// Suscribe to all state changes
const unsubscribe = subscribe(state, () => console.log(`state has changed to ${state}`))
// Unsubscribe by calling the result
unsubscribe()
// Subscribe to a portion of state
subscribe(state.foo, () => console.log(`state.foo has changed to ${state.foo}`))
And that's it!