Skip to curriculum
Jump to the editor

19.7. Reactive state that tracks what it reads

Hard
Topics
35–60 min

A price label, a cart total and a "Checkout" button all depend on the same few values. Instead of calling update() by hand after every change, a reactive system records which values each piece of code read, and runs that code again when one of them changes. This is how signals in modern UI libraries work: no subscriptions to write, just reads.

Write three functions in reactive.js: signal holds a value, effect runs code that reads signals and re-runs it when they change, and batch groups several changes into one round of re-runs.

Signature

JAVASCRIPT
function signal(initial) // returns { get(), set(next) }
function effect(fn)      // runs fn now; returns dispose()
function batch(fn)       // returns what fn returned
  • get() returns the current value. Called while an effect is running, it also records that effect as depending on this signal.
  • set(next) changes the value and re-runs the effects that depend on it.
  • dispose() stops the effect for good.

Requirements

  1. signal(initial) returns an object with get and set; get() returns the latest value set.
  2. effect(fn) runs fn once, synchronously, and returns a dispose function.
  3. An effect depends on exactly the signals it read during its last run. When one of them is set to a new value, the effect runs again, once, synchronously, inside set. Reading a signal several times in a run counts once; a signal it did not read never re-runs it.
  4. Dependencies are tracked again on every run: a signal read in an earlier run but not in the latest one no longer triggers the effect, and a newly read one does.
  5. set with a value that is Object.is equal to the current one does nothing (NaN equals NaN; 0 and -0 differ).
  6. A get() outside any running effect records nothing.
  7. Every effect that depends on a signal runs once per change, and notifying never loops forever, even though each effect re-subscribes while it re-runs.
  8. An effect that sets a signal it reads does not re-run itself because of that write. It may set signals that other effects read, and those effects run.
  9. Effects may be created inside effects. A read belongs to the innermost running effect, and once the inner effect finishes, the outer effect's reads are tracked again.
  10. dispose() stops all future runs of that effect only, may be called more than once, and may be called by the effect during its own run.
  11. If an effect throws, the error reaches the caller (of effect or set), and tracking keeps working for other effects.
  12. batch(fn) runs fn and returns its result. Effects affected by changes inside it run once each, after the outermost batch ends, even if fn throws. An effect disposed during the batch does not run. Changes made by those effects while they run are collected the same way: an effect that is still waiting runs once, with the final values, and one that already ran runs again only for a later change.

Examples

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

const dispose = effect(() => console.log(first.get(), last.get())); // "Ada Lovelace"
first.set("Augusta");  // "Augusta Lovelace"
first.set("Augusta");  // nothing: same value
dispose();
last.set("King");      // nothing: disposed
JAVASCRIPT
const showDetails = signal(false);
const details = signal("short");
effect(() => console.log(showDetails.get() ? details.get() : "hidden")); // "hidden"
details.set("long");     // nothing: the last run did not read details
showDetails.set(true);   // "long"
details.set("longer");   // "longer"
JAVASCRIPT
const a = signal(1);
const b = signal(2);
effect(() => console.log(a.get() + b.get())); // 3
batch(() => {
  a.set(10);
  b.set(20);
}); // 30, once, after the batch

Environment

  • Plain JavaScript in a browser page; the tests call the globals signal, effect and batch from reactive.js. You may add other top-level helpers and variables.
  • Effects run synchronously: no microtasks, timers or requestAnimationFrame.
  • Out of scope: computed (derived) signals, the order in which several effects of one signal run, and disposing inner effects automatically when the outer one re-runs.

Hints

  1. When get() runs, how can it know which effect is running right now, if effects can start inside other effects?
  2. To forget last run's dependencies, the effect needs to reach every signal's subscriber list it joined. What could it keep?
  3. What does a for...of loop over a Set do when a member is deleted and added again during the loop?

The explanation comes with the course

A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.

  • Every line explained
  • The mistakes each test catches
  • Links to the lessons behind it
Back to the question
Loading the editor…