subscribe

The subscribe function allows you to listen for changes to a proxy object from anywhere in your application, including outside of React components.

It returns an unsubscribe function that you can call to stop listening for updates.

Basic Usage

You can subscribe to all changes on a proxy and its nested properties.

import { proxy, subscribe } from 'valtio/vanilla';

const state = proxy({ count: 0 });

const unsubscribe = subscribe(state, () => {
  console.log('State has changed:', state);
});

state.count++; // Triggers the console.log

// Stop listening for changes
unsubscribe();

Subscribing to a Portion of State

You can also subscribe to a nested object within your proxy. The callback will only be triggered when that specific portion of the state changes.

const state = proxy({ 
  obj: { foo: 'bar' },
  arr: ['hello'] 
});

// This will only fire when `state.obj` or its properties change.
subscribe(state.obj, () => console.log('state.obj has changed to', state.obj));

// This will only fire when `state.arr` changes.
subscribe(state.arr, () => console.log('state.arr has changed to', state.arr));

state.obj.foo = 'baz'; // Triggers the first subscriber
state.arr.push('world'); // Triggers the second subscriber

Note: To subscribe to changes of a primitive property (e.g., state.count), use the subscribeKey utility. See the Utilities documentation for more details.

Vanilla JavaScript

subscribe is a core part of Valtio's vanilla API. To use it in a non-React project, import it from valtio/vanilla.

import { proxy, subscribe } from 'valtio/vanilla';

CodeSandbox Demo

See a vanilla JavaScript example of subscribe in action.

https://codesandbox.io/s/valtio-photo-booth-demo-forked-xp8hs?file=/src/main.js