Projects / Reactive library / Phase 3
Phase 3 of 4 · about 2.5 hours
Do less, control more
You end with batch, effects that skip work when a computed value did not really change, untracked, and effect cleanup. One experiment goes from 1,001 effect runs to 11.
Step 3.1: Batch writes (about 35 minutes)
Two writes in a row are two updates, and the effect runs twice, once on a half-updated state. Run try_batch.js after this step. We want to say "these writes are one change". Add a counter to the top of the file and make flush respect it:
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;
try {
while (queue.size > 0) {
const [next] = queue;
queue.delete(next);
next.run();
}
} finally {
flushing = false;
}
}
Then add batch below the Effect class:
export function batch(fn) {
batchDepth++;
try {
return fn();
} finally {
batchDepth--;
flush();
}
}
While batchDepth is above zero, flush returns at once, so effects queue up. When the outermost batch ends, it flushes once. The counter, rather than a true or false, is what lets batches nest: an inner one ends without flushing because the outer one is still open.
Step 3.2: Skip work when nothing really changed (about 55 minutes)
Look at the Phase 2 library. If n goes from 1 to 3, a computed n % 2 is marked stale, recalculated, and comes out as 1 again, but its observers were already told, and they run for nothing. The fix is to give every node a version number that goes up only when its value really changes. An observer remembers the version it saw. Before running, it checks whether any source's version moved.
Replace Node:
class Node {
sources = new Map(); // source -> the version we saw when we read it
observers = new Set();
version = 0;
subscribe() {
if (active) {
this.observers.add(active);
active.sources.set(this, this.version);
}
}
collect(fn) {
this.unsubscribe();
const previous = active;
active = this;
try {
return fn();
} finally {
active = previous;
}
}
unsubscribe() {
for (const source of this.sources.keys()) source.observers.delete(this);
this.sources.clear();
}
// Did anything we read really change? Computed values are brought up to date first.
sourcesChanged() {
for (const [source, seen] of this.sources) {
source.refresh?.();
if (source.version !== seen) return true;
}
return false;
}
markStale() {}
}
sources is now a Map from each source to the version we saw. sourcesChanged walks it, refreshes computed sources first, and answers true if any version differs. Now Signal and 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;
this.version++;
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;
}
refresh() {
if (!this.#stale) return;
if (this.version > 0 && !this.sourcesChanged()) {
this.#stale = false;
return;
}
const next = this.collect(this.fn);
if (this.version === 0 || !Object.is(next, this.#value)) this.version++;
this.#value = next;
this.#stale = false;
}
get value() {
this.refresh();
this.subscribe();
return this.#value;
}
peek() {
this.refresh();
return this.#value;
}
markStale() {
if (this.#stale) return;
this.#stale = true;
for (const observer of this.observers) observer.markStale();
}
}
A signal bumps its version when written. A computed splits its work into refresh. If it is stale but none of its sources really changed, it just clears the flag. If it recalculates and gets an equal value, its version stays put, so nothing downstream moves. Last, Effect and the helpers:
export class Effect extends Node {
disposed = false;
#cleanup;
#ran = false;
constructor(fn) {
super();
this.fn = fn;
this.run();
}
run() {
if (this.disposed) return;
if (this.#ran && !this.sourcesChanged()) return;
this.#ran = true;
this.#cleanup?.();
const result = this.collect(this.fn);
this.#cleanup = typeof result === 'function' ? result : undefined;
}
markStale() {
queue.add(this);
}
dispose() {
this.disposed = true;
this.unsubscribe();
queue.delete(this);
this.#cleanup?.();
this.#cleanup = undefined;
}
}
run now starts with a check: after the first run, do nothing unless a source version moved. The lines about #cleanup are for Step 3.3.
Run it. Create try_versions.js:
import { signal, computed, effect } from './signals.js';
const n = signal(1);
let parityRuns = 0;
let effectRuns = 0;
const parity = computed(() => {
parityRuns++;
return n.value % 2 === 0 ? 'even' : 'odd';
});
effect(() => {
effectRuns++;
console.log('parity is', parity.value);
});
n.value = 3; // still odd
n.value = 5; // still odd
console.log('computed runs:', parityRuns, '| effect runs:', effectRuns);
n.value = 6; // now even
console.log('computed runs:', parityRuns, '| effect runs:', effectRuns);
parity is odd
computed runs: 3 | effect runs: 1
parity is even
computed runs: 4 | effect runs: 2
The computed ran for each change, since it has to see the new number. The effect did not. Going from 1 to 3 and then 5 left the parity odd, so the effect ran once at the start and once more at 6.
Step 3.3: Untracked reads and cleanup (about 30 minutes)
Two more tools. untracked reads signals without subscribing to them, handy for "use the current value but do not re-run when it changes". Add below batch:
export function untracked(fn) {
const previous = active;
active = null;
try {
return fn();
} finally {
active = previous;
}
}
It sets active to nothing for the duration and puts it back afterwards. The second tool is cleanup: if your effect function returns a function, we remember it and call it before the next run and when the effect is disposed. You saw that code in Effect.run already. Use both. Create try_cleanup.js:
import { signal, effect, untracked } from './signals.js';
const room = signal('kitchen');
const volume = signal(3);
const listener = effect(() => {
const name = room.value;
const level = untracked(() => volume.value); // read it, but do not depend on it
console.log(`listening to ${name} at volume ${level}`);
return () => console.log(`stopped listening to ${name}`);
});
room.value = 'garden';
volume.value = 9; // untracked: no run
room.value = 'garage';
listener.dispose();
listening to kitchen at volume 3
stopped listening to kitchen
listening to garden at volume 3
stopped listening to garden
listening to garage at volume 9
stopped listening to garage
Each new room first stops listening to the old one. Changing volume caused no run because it was read through untracked, but the next run still picked up the new value, 9. Disposing runs the cleanup one last time.
Now the batch script from Step 3.1:
import { signal, effect, batch } from './signals.js';
const first = signal('Ada');
const last = signal('Lovelace');
let runs = 0;
effect(() => {
runs++;
console.log(`full name: ${first.value} ${last.value}`);
});
console.log('--- two writes, no batch');
first.value = 'Grace';
last.value = 'Hopper';
console.log('runs so far:', runs);
console.log('--- two writes in a batch');
batch(() => {
first.value = 'Alan';
last.value = 'Turing';
});
console.log('runs so far:', runs);
full name: Ada Lovelace
--- two writes, no batch
full name: Grace Lovelace
full name: Grace Hopper
runs so far: 3
--- two writes in a batch
full name: Alan Turing
runs so far: 4
Without a batch, two writes made two runs and the first printed Grace Lovelace. In the batch, only Alan Turing, once.
Step 3.4: Count the savings (about 30 minutes)
A chain: a counter feeds bucket, which is the counter divided by 100 and rounded down, feeds label, which feeds an effect. We count 1,000 writes. Create try_savings.js:
import { signal, computed, effect } from './signals.js';
const n = signal(0);
let bucketRuns = 0;
let effectRuns = 0;
const bucket = computed(() => {
bucketRuns++;
return Math.floor(n.value / 100);
});
const label = computed(() => `bucket ${bucket.value}`);
effect(() => {
effectRuns++;
label.value;
});
for (let i = 1; i <= 1000; i++) n.value = i;
console.log('writes: 1000 | bucket runs:', bucketRuns, '| effect runs:', effectRuns);
writes: 1000 | bucket runs: 1001 | effect runs: 11
The bucket computed had to run for every write, 1,001 times, since it must see each new number. But the effect ran only 11 times: once at the start and once each time the bucket really changed. The same script on the Phase 2 library gives 1,001 effect runs: the effect ran on every write for no reason.
Phase 3 done
Your library batches writes, skips work, reads without subscribing and cleans up after itself.