Course contentsShow
← JavaScript
Lesson 2126 of 2,72344. Reactive PatternsFree lesson

Implementing a Minimal Signal System

Building a simple signal implementation from scratch to understand the core mechanics of dependency tracking and reactive updates.

Implementing a Minimal Signal System

You'll learn how to build a bare-bones signal system from scratch, exposing the core mechanics of automatic dependency tracking and reactive updates.

The Core Idea

A signal system needs three pieces: signals (reactive values), computed values (derived signals), and effects (side effects that auto-rerun). The magic happens through dependency tracking: when a computed or effect reads a signal, that signal remembers "who's listening," so it can notify them when it changes.

Think of it like a spreadsheet: when cell C1 contains =A1+B1, changing A1 or B1 automatically updates C1. Your signal system does this programmatically.

Minimal Implementation

let currentListener = null;

function createSignal(initialValue) {
  let value = initialValue;
  const subscribers = new Set();

  return {
    get() {
      if (currentListener) subscribers.add(currentListener);
      return value;
    },
    set(newValue) {
      value = newValue;
      subscribers.forEach(fn => fn());
    }
  };
}

function createEffect(fn) {
  currentListener = fn;
  fn(); // Run once to establish dependencies
  currentListener = null;
}

How It Works

When createEffect runs, it sets a global currentListener. If the effect reads any signal via .get(), that signal captures the listener in its subscribers set. Later, when .set() is called, all subscribers rerun.

const count = createSignal(0);
createEffect(() => console.log("Count:", count.get())); // Logs "Count: 0"
count.set(5); // Logs "Count: 5"

This minimal system lacks batching, computed signals, and cleanup, but it demonstrates the essential pattern: capture dependencies during execution, then notify dependents on change.

Key Takeaway: A minimal signal system uses a global context variable to track which effect is currently running, allowing signals to automatically register subscribers and trigger reruns when values change—the foundation of all reactive frameworks.