subscribe
Subscribe from anywhere
You can access state outside your components and subscribe to changes.
import { proxy, subscribe } from 'valtio'
const state = proxy({ count: 0 })
// Subscribe to all changes to the state proxy (and its child proxies)
const unsubscribe = subscribe(state, () =>
console.log('state has changed to', state),
)
// Unsubscribe by calling the result
unsubscribe()
You can also subscribe to a portion of state.
const state = proxy({ obj: { foo: 'bar' }, arr: ['hello'] })
subscribe(state.obj, () => console.log('state.obj has changed to', state.obj))
state.obj.foo = 'baz'
subscribe(state.arr, () => console.log('state.arr has changed to', state.arr))
state.arr.push('world')