Vanilla JavaScript Projects

Project 15, Modern UI

Signals State Library

Signals are how modern frameworks know what to update. This page builds the whole idea in about 40 lines, then uses it to run a shopping cart.

signalcomputedeffect
Core idea
Signals, computed, effect
Size
About 40 lines
Dependencies
None
Your browser
Checking

Shopping cart

Every number here is a signal or a computed value. Nothing re-renders the whole page.

    ItemsSubtotalDiscountTotal

    Effect runs

    Each line counts how often that effect ran. Change a quantity and only the affected ones tick up.

      How it works

      1. Track readsWhen an effect runs, every signal it reads adds that effect to its subscriber list.
      2. Notify on writeSetting a signal schedules each subscriber once, in a microtask, so many writes cause one update.
      3. Derive valuescomputed() is an effect that writes into its own signal, so it caches and updates only when its inputs change.
      let current = null;
      export function signal(value) {
        const subs = new Set();
        const read = () => { if (current) subs.add(current); return value; };
        read.set = (v) => { if (v !== value) { value = v; subs.forEach(schedule); } };
        return read;
      }
      export function effect(fn) {
        const run = () => { const prev = current; current = run; try { fn(); } finally { current = prev; } };
        run();
      }
      export function computed(fn) {
        const s = signal(); effect(() => s.set(fn())); return s;
      }