1. API
  2. subscribe

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')

Codesandbox demo in VanillaJS

Advanced: Listening to "Ops"

The subscribe callback can also receive Ops (Operations), which are detailed records of exactly what changed (e.g., which property was set or deleted). This is useful for advanced scenarios like synchronization or undo/redo.

Because tracking these operations has a small performance cost, they are disabled by default. For more details on how to enable and use them, check out Subscribe Ops.