DEV Community

Rich Polo
Rich Polo

Posted on

Reactive signals in 45 lines of JavaScript (and how dependency tracking actually works)

Signals are everywhere now: Solid, Preact, Angular, Vue's ref, and a TC39 proposal to put them in the language. The API looks magical: you read a value inside an effect and the effect somehow "knows" to re-run when that value changes. No dependency arrays, no subscriptions by hand.

The trick is small enough to build in one sitting. Here's a working version with signal, effect and computed, plus the tests I used to make sure it behaves.

The one idea: a global "who is reading right now?"

When an effect runs, we put it in a module-level variable. Any signal read during that run sees the variable and adds the effect to its subscriber list. That's the whole dependency tracking system.

let currentObserver = null;

function signal(initial) {
  let value = initial;
  const subscribers = new Set();
  const read = () => {
    if (currentObserver) {
      subscribers.add(currentObserver);
      currentObserver.sources.add(subscribers);
    }
    return value;
  };
  const write = (next) => {
    if (Object.is(next, value)) return;
    value = next;
    for (const sub of [...subscribers]) sub.run();
  };
  return [read, write];
}
Enter fullscreen mode Exit fullscreen mode

Two small details matter:

  • Object.is skips updates when nothing changed, so setting 3 to 3 doesn't wake anyone up (and handles NaN correctly, unlike ===).
  • We iterate over a copy ([...subscribers]). Running an effect removes and re-adds it to the set; mutating a Set while looping over it can visit the same item again and loop forever.

Effects that re-track on every run

function effect(fn) {
  const observer = {
    sources: new Set(),
    run() {
      for (const subs of observer.sources) subs.delete(observer);
      observer.sources.clear();
      const prev = currentObserver;
      currentObserver = observer;
      try { fn(); } finally { currentObserver = prev; }
    },
  };
  observer.run();
  return () => {
    for (const subs of observer.sources) subs.delete(observer);
    observer.sources.clear();
  };
}
Enter fullscreen mode Exit fullscreen mode

Before every run, the effect unsubscribes from everything and then re-subscribes to whatever it reads this time. That gives you dynamic dependencies for free:

effect(() => console.log(useA() ? a() : b()));
Enter fullscreen mode Exit fullscreen mode

While useA() is true, changes to b are ignored, because b was never read. Flip useA and the effect starts tracking b and drops a.

Saving and restoring prev (instead of setting currentObserver = null) makes nested effects work, and the try/finally keeps tracking sane even if fn throws.

The returned function disposes the effect. Forgetting to call it is the classic memory leak in every signals library: the signal keeps a reference to the effect forever.

Computed values are just an effect writing to a signal

function computed(fn) {
  const [read, write] = signal(undefined);
  effect(() => write(fn()));
  return read;
}
Enter fullscreen mode Exit fullscreen mode

It reads like cheating, but it works: the inner effect tracks whatever fn reads, and the result goes into a signal that other effects can depend on.

const [celsius, setCelsius] = signal(0);
const fahrenheit = computed(() => celsius() * 9 / 5 + 32);

effect(() => console.log(`${celsius()}°C = ${fahrenheit()}°F`));
setCelsius(100);
Enter fullscreen mode Exit fullscreen mode

Actual output from running this:

0°C = 32°F
100°C = 212°F
100°C = 212°F
Enter fullscreen mode Exit fullscreen mode

Notice the duplicate line. The effect depends on celsius and on fahrenheit, and both change, so it runs twice. The values happen to be right here because the computed was subscribed first and updated first, but with a different subscription order the first run could see a stale value. That's the "glitch" problem I come back to at the end, and it's the main thing real libraries solve.

Tests

I ran these with Node's built-in runner (node --test), no framework needed:

  1. a signal reads back what was written;
  2. an effect runs once immediately and again on each change;
  3. writing the same value doesn't re-run effects;
  4. computed updates when either input changes;
  5. dynamic dependencies: the branch not taken isn't tracked;
  6. the dispose function stops future runs;
  7. an effect that reads a computed updates through the chain;
  8. the double run from the Celsius example, pinned as a known limitation so I notice if a refactor changes it.
ℹ tests 8
ℹ pass 8
ℹ fail 0
Enter fullscreen mode Exit fullscreen mode

What this toy version doesn't do (and real libraries do)

  • Glitches. Our updates are eager and depth-first. As in the Celsius example, an effect that reads a signal both directly and through a computed (or a "diamond" of two computeds) runs more than once per change and may briefly see one fresh and one stale value. Real libraries mark nodes dirty first, then recompute in topological order.
  • Laziness. Our computed recalculates even if nobody reads it. Solid and Preact only recompute on read.
  • Batching. Setting three signals runs effects three times. A batch(() => {...}) helper that defers effects until the end is a nice exercise to add.
  • Equality per signal, error boundaries, cleanup callbacks inside effects, scheduling with microtasks…

But the core, a global "current observer" plus sets of subscribers, is exactly the same. Once you've written it yourself, the framework versions stop feeling like magic.

Have you tried adding batch() to something like this? I'd love to see how others handle the scheduling part.

Top comments (0)