snippetjavascriptModeratepending
Observable/Signal pattern -- reactive state in vanilla JS
Viewed 0 times
signalobservablereactivesubscribenotifystate management
browsernodejs
Problem
Need reactive state that automatically notifies subscribers when values change, without pulling in a full framework like RxJS or MobX.
Solution
Build a minimal signal/observable that tracks subscribers and notifies on change. This is the core primitive behind Solid.js, Angular signals, and Preact signals.
Code Snippets
Minimal signal/reactive system
function signal(initial) {
let value = initial;
const subs = new Set();
return {
get() { return value; },
set(next) {
if (next === value) return;
value = next;
subs.forEach(fn => fn(value));
},
subscribe(fn) {
subs.add(fn);
return () => subs.delete(fn);
},
};
}
function computed(deps, fn) {
const s = signal(fn());
deps.forEach(d => d.subscribe(() => s.set(fn())));
return { get: s.get, subscribe: s.subscribe };
}
// Usage
const count = signal(0);
const doubled = computed([count], () => count.get() * 2);
doubled.subscribe(v => console.log('doubled:', v));
count.set(5); // logs: doubled: 10Revisions (0)
No revisions yet.