Skip to main content
Module

x/valtio/docs/advanced/subscribe.mdx

πŸ’Š Valtio makes proxy-state simple for React and Vanilla
Go to Latest
File
---title: 'subscribe'section: 'Advanced'description: 'Subscribe to a current state/object'---
# subscribe
#### Subscribe from anywhere
You can access state outside of your components and subscribe to changes.
```jsximport { subscribe } from 'valtio'
// Subscribe to all state changesconst unsubscribe = subscribe(state, () => console.log('state has changed to', state))// Unsubscribe by calling the resultunsubscribe()```
You can also subscribe to a portion of state.
```jsxconst 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
https://codesandbox.io/s/valtio-photo-booth-demo-forked-xp8hs?file=/src/main.js