knaxuslearn · build · ship

Projects / Reactive library / Phase 4

Phase 4 of 4 · about 2.5 hours

Make it a package

You end with a package with tests and a benchmark that you install from another folder and use.

Step 4.1: A guard against loops (about 30 minutes)

An effect that writes the signal it reads will trigger itself forever. Better to fail with a message. Add a limit at the top of the file and count runs in flush:

const MAX_RUNS = 100; // one flush may run this many effects before we call it a loop

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

function flush() {
  if (flushing || batchDepth > 0) return;
  flushing = true;
  let runs = 0;
  try {
    while (queue.size > 0) {
      if (++runs > MAX_RUNS) {
        queue.clear();
        throw new Error(
          'Effects keep triggering each other: is one writing a signal it also reads?',
        );
      }
      const [next] = queue;
      queue.delete(next);
      next.run();
    }
  } finally {
    flushing = false;
  }
}

Create try_loop.js:

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

const counter = signal(0);
try {
  effect(() => {
    counter.value = counter.value + 1; // reads and writes the same signal
  });
} catch (error) {
  console.log('caught:', error.message);
}
console.log('counter stopped at', counter.peek());
caught: Effects keep triggering each other: is one writing a signal it also reads?
counter stopped at 101

The effect added one a hundred times, then we stopped it with an error that says what is probably wrong. Without the guard this script would never end.

Step 4.2: Tests (about 40 minutes)

Node ships a test runner, so no packages are needed. Create signals.test.js. Each test states one promise the library makes:

import test from 'node:test';
import assert from 'node:assert/strict';
import { signal, computed, effect, batch, untracked } from './signals.js';

test('an effect runs once at the start and again when a signal it read changes', () => {
  const count = signal(0);
  const seen = [];
  effect(() => seen.push(count.value));
  count.value = 1;
  count.value = 1; // same value
  assert.deepEqual(seen, [0, 1]);
});

test('an effect stops watching what it no longer reads', () => {
  const show = signal(true);
  const name = signal('Ada');
  let runs = 0;
  effect(() => {
    runs++;
    if (show.value) name.value;
  });
  show.value = false;
  name.value = 'Grace';
  assert.equal(runs, 2);
});

test('a computed value is lazy and cached', () => {
  const n = signal(2);
  let runs = 0;
  const double = computed(() => (runs++, n.value * 2));
  assert.equal(runs, 0);
  assert.equal(double.value, 4);
  assert.equal(double.value, 4);
  assert.equal(runs, 1);
  n.value = 5;
  assert.equal(runs, 1);
  assert.equal(double.value, 10);
  assert.equal(runs, 2);
});

test('a diamond runs the effect once, with consistent values', () => {
  const n = signal(1);
  const double = computed(() => n.value * 2);
  const square = computed(() => n.value * n.value);
  const seen = [];
  effect(() => seen.push([double.value, square.value]));
  n.value = 3;
  assert.deepEqual(seen, [
    [2, 1],
    [6, 9],
  ]);
});

test('an effect does not rerun when a computed value comes out the same', () => {
  const n = signal(1);
  const parity = computed(() => n.value % 2);
  let runs = 0;
  effect(() => (runs++, parity.value));
  n.value = 3;
  n.value = 5;
  assert.equal(runs, 1);
  n.value = 6;
  assert.equal(runs, 2);
});

test('batch runs each effect once, after the last write', () => {
  const a = signal(1);
  const b = signal(2);
  const seen = [];
  effect(() => seen.push(a.value + b.value));
  batch(() => {
    a.value = 10;
    b.value = 20;
  });
  assert.deepEqual(seen, [3, 30]);
});

test('batch returns what its function returns, and nested batches wait for the outer one', () => {
  const a = signal(0);
  let runs = 0;
  effect(() => (runs++, a.value));
  const result = batch(() => {
    batch(() => (a.value = 1));
    assert.equal(runs, 1);
    return 'done';
  });
  assert.equal(result, 'done');
  assert.equal(runs, 2);
});

test('untracked reads do not subscribe', () => {
  const a = signal(1);
  const b = signal(1);
  let runs = 0;
  effect(() => {
    runs++;
    a.value;
    untracked(() => b.value);
  });
  b.value = 2;
  assert.equal(runs, 1);
});

test('cleanup runs before the next run and on dispose', () => {
  const a = signal(1);
  const log = [];
  const e = effect(() => {
    log.push(`start ${a.value}`);
    return () => log.push(`stop ${a.value}`);
  });
  a.value = 2;
  e.dispose();
  assert.deepEqual(log, ['start 1', 'stop 2', 'start 2', 'stop 2']);
});

test('a disposed effect never runs again', () => {
  const a = signal(0);
  let runs = 0;
  const e = effect(() => (runs++, a.value));
  e.dispose();
  a.value = 1;
  assert.equal(runs, 1);
});

test('an effect that keeps triggering itself throws instead of hanging', () => {
  const a = signal(0);
  assert.throws(() => effect(() => (a.value = a.value + 1)), /keep triggering/);
});

test('an error inside an effect does not break later updates', () => {
  const a = signal(0);
  const seen = [];
  effect(() => {
    if (a.value === 1) throw new Error('boom');
    seen.push(a.value);
  });
  assert.throws(() => (a.value = 1), /boom/);
  a.value = 2;
  assert.deepEqual(seen, [0, 2]);
});
node --test --test-reporter=spec
✔ an effect runs once at the start and again when a signal it read changes (1.801382ms)
✔ an effect stops watching what it no longer reads (1.65454ms)
✔ a computed value is lazy and cached (0.342424ms)
✔ a diamond runs the effect once, with consistent values (0.313638ms)
✔ an effect does not rerun when a computed value comes out the same (0.312848ms)
✔ batch runs each effect once, after the last write (0.260194ms)
✔ batch returns what its function returns, and nested batches wait for the outer one (0.157938ms)
✔ untracked reads do not subscribe (0.146909ms)
✔ cleanup runs before the next run and on dispose (0.514979ms)
✔ a disposed effect never runs again (0.391823ms)
✔ an effect that keeps triggering itself throws instead of hanging (0.748393ms)
✔ an error inside an effect does not break later updates (0.241809ms)
ℹ tests 12
ℹ pass 12
ℹ fail 0

Every promise from the first three phases is now checked, and so are two new ones: errors inside an effect do not break later updates, and nested batches wait for the outer one.

Step 4.3: A benchmark that finds a bug (about 40 minutes)

How fast is it? Create bench.js with three shapes: many writes, a long chain and a wide fan-out:

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

function time(label, fn) {
  const start = performance.now();
  fn();
  console.log(`${label.padEnd(44)} ${(performance.now() - start).toFixed(0).padStart(5)} ms`);
}

time('100,000 writes, one effect watching', () => {
  const s = signal(0);
  let sum = 0;
  effect(() => (sum += s.value));
  for (let i = 1; i <= 100_000; i++) s.value = i;
});

time('chain of 1,000 computed, 100 writes', () => {
  const s = signal(0);
  let last = computed(() => s.value);
  for (let i = 0; i < 999; i++) {
    const previous = last;
    last = computed(() => previous.value + 1);
  }
  effect(() => last.value);
  for (let i = 1; i <= 100; i++) s.value = i;
});

time('1,000 effects on one signal, 100 writes', () => {
  const s = signal(0);
  for (let i = 0; i < 1000; i++) effect(() => s.value);
  for (let i = 1; i <= 100; i++) s.value = i;
});
node bench.js
100,000 writes, one effect watching             44 ms
chain of 1,000 computed, 100 writes             35 ms
Error: Effects keep triggering each other: is one writing a signal it also reads?

The first two numbers are fine. The third one never finishes: it throws our loop error, with no loop in sight. A thousand effects watch one signal, and one write queues a thousand effects. Our guard counted every effect run in a flush, and 1,000 is more than 100.

The test suite did not catch it, because no test had that many effects. A guard against loops should count how often the same effect runs, not how many effects run. Replace flush and the constant at the top of the file:

const MAX_RUNS = 100; // one effect may run this many times in one flush before we call it a loop

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

function flush() {
  if (flushing || batchDepth > 0) return;
  flushing = true;
  const runs = new Map(); // how many times each effect has run in this flush
  try {
    while (queue.size > 0) {
      const [next] = queue;
      queue.delete(next);
      const count = (runs.get(next) ?? 0) + 1;
      runs.set(next, count);
      if (count > MAX_RUNS) {
        queue.clear();
        throw new Error(
          'Effects keep triggering each other: is one writing a signal it also reads?',
        );
      }
      next.run();
    }
  } finally {
    flushing = false;
  }
}

Each effect has its own count in a Map. One effect running more than 100 times in one flush is a loop. A thousand effects each running once is not.

node bench.js
node --test --test-reporter=spec
100,000 writes, one effect watching             58 ms
chain of 1,000 computed, 100 writes             41 ms
1,000 effects on one signal, 100 writes         77 ms
ℹ tests 12
ℹ pass 12
ℹ fail 0

All three run, and the tests still pass. Your timings will be different. The shape to look for is that each case finishes in tens of milliseconds, which is a sign that nothing in the update path is quadratic for these cases.

Pitfall: a very deep chain, say 100,000 computeds, would overflow the call stack, because marking and refreshing call each other recursively. We did not test that, and real libraries use loops there.

Step 4.4: Package it (about 40 minutes)

A package has a single entry point and says which files belong to it. Create index.js:

export { signal, computed, effect, batch, untracked, Signal, Computed, Effect } from './signals.js';

Replace package.json:

{
  "name": "tiny-signals",
  "version": "0.1.0",
  "description": "A small signals library: signal, computed, effect and batch.",
  "type": "module",
  "exports": "./index.js",
  "files": ["index.js", "signals.js"],
  "scripts": {
    "test": "node --test"
  },
  "license": "MIT"
}

exports says what import 'tiny-signals' loads. files lists what goes into the package: your tests and benchmark stay behind. Build a tarball, which is what a registry would store:

npm pack

Then use it from somewhere else. In a new folder, install the tarball and write app.mjs:

mkdir ../app && cd ../app && npm init -y
npm install ../signals/tiny-signals-0.1.0.tgz
import { signal, computed, effect } from 'tiny-signals';

const celsius = signal(20);
const fahrenheit = computed(() => celsius.value * 1.8 + 32);
effect(() => console.log(`${celsius.value} C is ${fahrenheit.value} F`));
celsius.value = 100;
node app.mjs
20 C is 68 F
100 C is 212 F

Your library works from a different folder, through its package name. Choose your own package name before you ever publish anything, since this one may belong to someone else.

Phase 4 done

You wrote about 170 lines of library, 12 tests and a benchmark, and shipped it as an installable package. That is the core of what signals libraries in frameworks do.