JavaScript

Observable / Reactive State

by @admin
9h ago
Apr 28, 2026
Public
A minimal reactive state container. Wrap any object with observable() and it returns a Proxy that notifies subscribers whenever a property is set. subscribe() registers a listener that receives the changed key and new value. A lightweight alternative to MobX or Vue's reactive() for small-scale reactivity needs.
JavaScript
function observable(initialState) {
  const listeners = new Set();
  const state = new Proxy(initialState, {
    set(target, key, value) {
      target[key] = value;
      listeners.forEach((fn) => fn(key, value, target));
      return true;
    },
  });
  return {
    state,
    subscribe(fn) {
      listeners.add(fn);
      return () => listeners.delete(fn);
    },
  };
}

// Usage
const { state, subscribe } = observable({ count: 0, name: 'Alice' });
subscribe((key, val) => console.log(`${key} changed to`, val));
state.count++;    // count changed to 1
state.name = 'Bob'; // name changed to Bob
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.