knaxuslearn · build · ship

Projects / Reactive library / Phase 1

Phase 1 of 4 · about 2.5 hours

Notice what was read

You end with an effect that re-runs exactly when something it read changes, stops watching what it no longer reads, and a visible glitch that Phase 2 will fix.

Three words first. A signal is a box holding a value. An effect is a function that runs now and runs again when a signal it used changes. The trick that ties them together is dependency tracking: while an effect runs, every signal it reads notes down who is reading. Nobody lists dependencies by hand.

Step 1.1: A box that remembers who looked (about 30 minutes)

Create signals.js. The Signal class holds a value in a private field, and keeps a set of observers, the effects that read it. A module-level variable, active, points to the effect that is running right now.

let active = null; // the effect that is running right now, if any

export class Signal {
  #value;
  observers = new Set();

  constructor(value) {
    this.#value = value;
  }

  get value() {
    if (active) {
      this.observers.add(active);
      active.sources.add(this);
    }
    return this.#value;
  }

  set value(next) {
    if (Object.is(next, this.#value)) return;
    this.#value = next;
    for (const observer of [...this.observers]) observer.run();
  }

  peek() {
    return this.#value;
  }
}

Reading value does two jobs. If an effect is running, both sides note each other down. Then it returns the value. Writing value skips the work when nothing changed, using Object.is so that NaN equals NaN. Otherwise it stores the value and runs every observer. We copy the set with [...] because a run may change the set while we loop.

Try it. Create try_signal.js:

import { signal } from './signals.js';

const count = signal(0);
console.log('start:', count.value);
count.value = 5;
console.log('after set:', count.value);
count.value = 5; // same value: nothing changes
console.log('observers:', count.observers.size);
start: 0
after set: 5
observers: 0

Nothing reads the signal inside an effect yet, so it has no observers. Setting the same value twice does nothing visible.

Step 1.2: An effect that follows its reads (about 40 minutes)

Now the other half. Add this below Signal:

export class Effect {
  sources = new Set();

  constructor(fn) {
    this.fn = fn;
    this.run();
  }

  run() {
    this.unsubscribe();
    const previous = active;
    active = this;
    try {
      this.fn();
    } finally {
      active = previous;
    }
  }

  unsubscribe() {
    for (const source of this.sources) source.observers.delete(this);
    this.sources.clear();
  }

  dispose() {
    this.unsubscribe();
  }
}

run is the core of it. It first forgets everything the effect used to watch, then sets active to itself, calls your function, and puts active back in a finally, so an error cannot leave the wrong effect marked as running. Every .value read inside your function now registers us. Add two small helpers at the bottom:

export const signal = (value) => new Signal(value);
export const effect = (fn) => new Effect(fn);

Create try_effect.js:

import { signal, effect } from './signals.js';

const count = signal(0);
effect(() => {
  console.log('count is', count.value);
});
count.value = 1;
count.value = 2;
count.value = 2; // same value, no run
console.log('observers of count:', count.observers.size);
count is 0
count is 1
count is 2
observers of count: 1

The effect printed once at the start and then once for each real change. The same-value write printed nothing, and count has exactly one observer.

Step 1.3: Watch only what you read (about 40 minutes)

Look again at the first line of run: it unsubscribes before every run. That matters when an effect's reads depend on a condition. Create try_dynamic.js:

import { signal, effect } from './signals.js';

const showName = signal(true);
const name = signal('Ada');
const other = signal('unused');
let runs = 0;

effect(() => {
  runs++;
  console.log(showName.value ? `name: ${name.value}` : 'hidden');
});

console.log('runs after start:', runs, '| name observers:', name.observers.size);
other.value = 'changed'; // never read: no run
console.log('runs after other changed:', runs);
showName.value = false;
console.log('runs after hiding:', runs, '| name observers:', name.observers.size);
name.value = 'Grace'; // the effect no longer reads name
console.log('runs after name changed while hidden:', runs);
name: Ada
runs after start: 1 | name observers: 1
runs after other changed: 1
hidden
runs after hiding: 2 | name observers: 0
runs after name changed while hidden: 2

While showName is true, the effect reads name, so name has an observer. After hiding, the effect runs again, takes the other branch, and does not read name. Because we cleared its subscriptions first, name has no observers any more, and changing it costs nothing. other was never read, so changing it never caused a run.

Pitfall: without the unsubscribe, the effect would stay subscribed to name forever and re-run for nothing.

Step 1.4: Stop watching, and meet the glitch (about 40 minutes)

dispose in the class is how you stop an effect: it unsubscribes and never runs again. Let's use it and, at the same time, look at something that is wrong. Create try_glitch.js:

import { signal, effect } from './signals.js';

const first = signal('Ada');
const last = signal('Lovelace');

const watcher = effect(() => {
  console.log('full name:', first.value, last.value);
});

console.log('--- changing both names');
first.value = 'Grace';
last.value = 'Hopper';

watcher.dispose();
console.log('--- after dispose');
first.value = 'Alan';
last.value = 'Turing';
console.log('nothing printed above this line');
full name: Ada Lovelace
--- changing both names
full name: Grace Lovelace
full name: Grace Hopper
--- after dispose
nothing printed above this line

Two things happened. After dispose, nothing prints. And before it, changing the first name and then the last name printed Grace Lovelace, a name that never existed. The effect ran right after the first write, while the data was half updated. That is a glitch: an effect seeing an inconsistent state. In Phase 2 we stop effects from running in the middle of an update.

Phase 1 done

You have a library that tracks its own dependencies. It also runs effects too early, and it has nothing for derived values yet.