Skip to content
jshacks.dev
Async

Signals and Reactive Programming in JavaScript

Learn what signals are, how a signal, a computed value and an effect track dependencies automatically, and how they differ from observables and event handlers.

7 min read
Summarize in AI
Flat illustration of a component talking to the server without a page load, with the JavaScript, Svelte, React and Vue.js logos.

A signal is a value that knows who depends on it. When you read a signal inside a computed value or an effect, the system records the dependency. When you later change the signal, only the things that read it are recomputed or rerun, and nothing else. That is the whole idea, and it has spread through nearly every UI framework in the last few years: Solid built on it, Vue's ref is one, Angular added signal(), Preact exposes @preact/signals, and Svelte 5 uses them under its runes. There is also a TC39 proposal to put signals in the language itself, which is at an early stage and not yet part of any standard. This post builds a tiny signal system from scratch in about thirty lines so the mechanism is visible, shows signal, computed and effect with printed output, compares signals with observables and event handlers and explains the pitfalls that come from automatic dependency tracking.

The three pieces

A signal holds a value and notifies readers when it changes. A computed is a value derived from other signals, recomputed only when one of them changes. An effect is a function that runs for its side effects, such as updating the DOM, and reruns when any signal it read changes.

Here is the behavior you get from any signal library, using the Preact signals API as the example.

JavaScript
import { signal, computed, effect } from "@preact/signals-core";

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

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

quantity.value = 3;
price.value = 20;
Text
total is 20
total is 30
total is 60

The effect ran once at the start with 20. Changing quantity recomputed total to 30, and the effect reran. Changing price made 60. You never said which signals the effect depends on, because reading .value told the system. That is automatic dependency tracking, and it is what separates signals from manual subscription.

How it works: building one

The mechanism is a global "current subscriber" slot. When an effect runs, it sets itself as current. Any signal read during the run adds the current effect to its subscriber set. When the signal changes, it reruns its subscribers.

JavaScript
let currentEffect = null;

function signal(initial) {
  let value = initial;
  const subscribers = new Set();

  return {
    get value() {
      if (currentEffect) subscribers.add(currentEffect);
      return value;
    },
    set value(next) {
      if (Object.is(next, value)) return;
      value = next;
      for (const run of [...subscribers]) run();
    },
  };
}

function effect(fn) {
  const run = () => {
    currentEffect = run;
    try {
      fn();
    } finally {
      currentEffect = null;
    }
  };

  run();
}

const count = signal(1);

effect(() => console.log("count is", count.value));

count.value = 2;
count.value = 2; // same value, no rerun
count.value = 5;
Text
count is 1
count is 2
count is 5

That is a working signal system, minus cleanup, batching and computed values. The setter compares with Object.is, so assigning the same value does nothing. Real libraries add dependency cleanup on each run, so an effect that stops reading a signal stops being notified, a topological ordering so computed values update before effects that use them and batching so several writes cause one update.

Computed values are lazy and cached

A computed recalculates only when read and only if a dependency changed since the last time.

JavaScript
import { signal, computed } from "@preact/signals-core";

const items = signal([3, 1, 2]);

let runs = 0;
const sorted = computed(() => {
  runs += 1;
  return [...items.value].sort();
});

console.log(sorted.value);
console.log(sorted.value);
console.log("computations:", runs);

items.value = [9, 8];

console.log(sorted.value);
console.log("computations:", runs);
Text
[ 1, 2, 3 ]
[ 1, 2, 3 ]
computations: 1
[ 8, 9 ]
computations: 2

Two reads cost one computation. The cache is invalidated only when items changes. This is the property that makes signals efficient for derived state: expensive work is done once, on demand and only when inputs change.

Batching

Several writes in a row should cause one update, not one each.

JavaScript
import { signal, effect, batch } from "@preact/signals-core";

const first = signal("Ada");
const last = signal("Lovelace");

effect(() => console.log(first.value, last.value));

batch(() => {
  first.value = "Grace";
  last.value = "Hopper";
});
Text
Ada Lovelace
Grace Hopper

Inside the batch, both writes happen and the effect reruns once at the end. Without batch, the effect would have printed the intermediate "Grace Lovelace", a state that never existed on purpose. Most frameworks batch automatically inside event handlers.

Signals versus observables

Both model values that change over time, and they differ in what they emphasize.

SignalObservable
Has a current valueAlways; you read it at any timeNo; you only receive emissions
Dependency trackingAutomatic, by readingManual, by subscribing and combining
ConsumersPull the latest value, and get notified of changeAre pushed each value
Operators over timeFew; mostly derived valuesMany: debounce, buffer, retry, switchMap
Best forUI state and derived valuesEvent streams and async flows

A signal is a variable with a notification system, and an observable is a stream of events. They complement each other. A common pattern is to model state as signals, and use observables for event sources with timing, then convert between them with helpers such as Angular's toSignal and toObservable.

Signals versus event handlers

An event handler runs when something happens and decides what to update. A signal-based design declares the relationship once and lets the system keep it up to date. The handler version has to remember every place that needs refreshing after each change, and forgetting one produces stale UI. The signal version cannot forget, because the dependency is the read.

JavaScript
import { signal, computed, effect } from "@preact/signals-core";

const todos = signal([{ done: true }, { done: false }, { done: false }]);
const remaining = computed(() => todos.value.filter((t) => !t.done).length);

effect(() => console.log(`${remaining.value} items left`));

todos.value = [...todos.value, { done: false }];
Text
2 items left
3 items left

Adding a todo updated the count without any code that says "when a todo is added, recompute the count".

Pitfalls

Mutation is invisible. A signal notices assignment, not mutation. Pushing onto an array held in a signal changes nothing that the system can see. Replace the value with a new array, as above.

JavaScript
const list = signal([1]);
list.value.push(2); // no notification
list.value = [...list.value, 3]; // notifies

Reads outside a tracking context are not tracked. Reading a signal in an event handler or a setTimeout callback gives the current value and subscribes to nothing. This is correct, and it surprises people who expect it to react.

Conditional reads change dependencies. In effect(() => flag.value ? a.value : b.value), the effect depends on flag and on whichever of a or b was read last. Libraries re-track on every run, so this works, but it explains why dependencies can seem to appear and disappear.

Effects that write signals can loop. An effect that reads and writes the same signal reruns itself without end. Libraries detect some cycles and throw, and others loop until a limit, so keep effects for outputs, such as the DOM, logging or network calls, and use computed values for derived state.

Cleanup. An effect that starts a timer or a subscription should return or register a cleanup function, which runs before the next run and on disposal. Dispose of effects created outside a component lifecycle, or they live as long as the signals they read.

The standard proposal

TC39 has a proposal for a Signal namespace, with Signal.State and Signal.Computed, intended as a shared core that frameworks build their own effects and scheduling on. It does not define effect on purpose, because scheduling is framework-specific. As of this writing, it is a proposal and not part of the language, so use a library or your framework's own implementation.

Adopting signals in practice

If your framework already ships signals, use them for the state that components share and for values derived from it, and keep short-lived local variables as plain variables. The common failure mode is overuse: wrapping every value in a signal adds overhead and ceremony, and gains nothing for values that never change or that nothing else reads. A good heuristic is to ask whether some other piece of code needs to react when this value changes. If yes, make it a signal. If not, leave it alone.

Debugging is also different. Because the update flow follows dependencies and not call stacks, a stack trace inside an effect shows the framework's scheduler and not the line that changed the value. Use the developer tools your framework provides to inspect the dependency graph, name your signals where the library allows it and log inside effects while you are getting oriented.

Share

Keep reading

Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.