knaxuslearn · build · ship

Projects / Reactive library / Phase 2

Phase 2 of 4 · about 2.5 hours

Derived values and calm updates

You end with computed values that are lazy and cached, and effects that run once per update with consistent values, even when two derived values share one source.

Step 2.1: Computed values (about 50 minutes)

A computed is a value derived from others, such as price * quantity. It should be calculated only when someone asks, and kept until something it used changes. That needs a way to say "your cached value is out of date" without recalculating straight away.

So every node gets a markStale method, and signals, computeds and effects share a base class. Replace everything in signals.js above export class Signal with this:

let active = null; // the node that is running right now, if any
const queue = new Set(); // effects waiting to run
let flushing = false;

function flush() {
  if (flushing) return;
  flushing = true;
  try {
    while (queue.size > 0) {
      const [next] = queue;
      queue.delete(next);
      next.run();
    }
  } finally {
    flushing = false;
  }
}

class Node {
  sources = new Set();
  observers = new Set();

  subscribe() {
    if (active) {
      this.observers.add(active);
      active.sources.add(this);
    }
  }

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

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

  markStale() {}
}

Three new things. The queue collects effects that should run, and flush runs them one at a time. Node holds what every kind of node needs: its sources, its observers, and the subscribe and collect helpers, which are the Phase 1 tracking code moved into one place. And markStale does nothing by default.

Now replace Signal and add Computed:

export class Signal extends Node {
  #value;

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

  get value() {
    this.subscribe();
    return this.#value;
  }

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

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

export class Computed extends Node {
  #value;
  #stale = true;

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

  get value() {
    this.subscribe();
    if (this.#stale) {
      this.#value = this.collect(this.fn);
      this.#stale = false;
    }
    return this.#value;
  }

  markStale() {
    if (this.#stale) return;
    this.#stale = true;
    for (const observer of this.observers) observer.markStale();
  }
}

Writing a signal no longer runs anything directly. It tells each observer it is stale, then calls flush. A Computed recalculates only in its value getter, and only if it is stale. When a computed is told it is stale, it marks itself and passes the news on to its own observers, once, because of the early return. Nothing is calculated during that spreading. Only marks move.

For now, make Effect keep working by leaving it as it is in Phase 1, and we replace it in the next step. Create try_computed.js:

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

const price = signal(10);
const quantity = signal(3);
let calculations = 0;

const total = computed(() => {
  calculations++;
  return price.value * quantity.value;
});

console.log('created, calculations:', calculations);
console.log('total:', total.value, '| calculations:', calculations);
console.log('total again:', total.value, '| calculations:', calculations);
price.value = 20;
console.log('price changed, calculations:', calculations);
console.log('total:', total.value, '| calculations:', calculations);

You can run it after the next step.

Step 2.2: Effects that wait their turn (about 40 minutes)

Replace Effect and the helpers at the bottom of the file:

export class Effect extends Node {
  disposed = false;

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

  run() {
    if (this.disposed) return;
    this.collect(this.fn);
  }

  markStale() {
    queue.add(this);
  }

  dispose() {
    this.disposed = true;
    this.unsubscribe();
    queue.delete(this);
  }
}

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

An effect told it is stale does not run. It joins the queue. flush runs the queue after the marking is done. Run the Step 2.1 script:

node try_computed.js
created, calculations: 0
total: 30 | calculations: 1
total again: 30 | calculations: 1
price changed, calculations: 1
total: 60 | calculations: 2

Follow the calculations counter. A computed does no work when created. The first read calculates once. The second read comes from the cache. Changing price does no work at all. The next read calculates again. That is the laziness and caching we wanted.

Now a computed inside an effect. Create try_effects.js:

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

const price = signal(10);
const quantity = signal(3);
const total = computed(() => price.value * quantity.value);

effect(() => {
  console.log('total is', total.value);
});

price.value = 20;
quantity.value = 5;
total is 30
total is 60
total is 100

Step 2.3: The diamond (about 30 minutes)

Here is the shape that breaks naive libraries. One signal feeds two computeds, and one effect reads both. Draw it and you get a diamond:

        n
       / \
  double  square
       \ /
      effect

When n changes, a careless library updates double, runs the effect, then updates square, and the effect saw a new double next to an old square. Ours marks everything first and runs effects after. Create try_diamond.js:

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

const n = signal(1);
const double = computed(() => n.value * 2);
const square = computed(() => n.value * n.value);

let runs = 0;
effect(() => {
  runs++;
  console.log(`n=${n.value} double=${double.value} square=${square.value}`);
});

n.value = 3;
console.log('effect runs:', runs);
n=1 double=2 square=1
n=3 double=6 square=9
effect runs: 2

The effect ran twice in total: once at the start and once for the change. Every line it printed is consistent, n, double and square agree. The glitch from Phase 1 came from running the effect in the middle of a write. Now the effect runs after all marks are placed.

One limit: two separate writes are still two updates. Phase 3 adds batch for that.

Step 2.4: Conditions inside computeds, and a leak (about 30 minutes)

Computeds track dependencies the same way effects do. Create try_branches.js:

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

const useShort = signal(true);
const short = signal('Ada');
const long = signal('Ada Lovelace');
let calculations = 0;

const label = computed(() => {
  calculations++;
  return useShort.value ? short.value : long.value;
});

console.log(label.value, '| calculations:', calculations);
long.value = 'Augusta Ada King'; // not read while useShort is true
console.log('stale after changing long?', label.value, '| calculations:', calculations);
useShort.value = false;
console.log(label.value, '| calculations:', calculations);
console.log('observers of short now:', short.observers.size);
Ada | calculations: 1
stale after changing long? Ada | calculations: 1
Augusta Ada King | calculations: 2
observers of short now: 0

While useShort is true, changing long does not even mark the computed stale: no extra calculation. After the switch, short has no observers. The same tracking ideas apply as in Phase 1.

Now the part that is not good. Create try_leak.js:

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

const source = signal(1);
for (let i = 0; i < 1000; i++) {
  const temporary = computed(() => source.value + i);
  temporary.value; // read once, then forget it
}
console.log('observers on source:', source.observers.size);
observers on source: 1000

We read 1,000 temporary computeds once each and threw them away, but the source still holds all 1,000 in its observers set, so they can never be freed. A computed that nobody observes stays subscribed to its sources. Real libraries solve this with ownership or weak references. We will keep it simple and name it as a limit in the wrap-up.

Phase 2 done

You have signal, computed and effect, the marks-then-run order, and a diamond that behaves. Next we make it do less work, and give you more control.