← Back to Angular, page 2

angular-0040 · Hard senior

How do signals work internally, including lazy computed values, memoization, equality checks, dynamic dependencies and untracked reads?

Signals form a dependency graph. A write marks dependents as possibly stale but does not recompute them (push). A read recomputes only what is actually stale (pull), and a computed whose new value equals the old one stops the change from spreading. Dependencies are recorded on each run, so they can change from run to run.

Full answer

Think of a signal as a node with a version number. A computed or an effect is a consumer. While a consumer runs, every signal it reads registers it as a dependency. This record is rebuilt on every run, so dependencies are dynamic: flag() ? a() : b() depends on b only while flag is false.

Writing a signal does two things. It bumps the version and walks its consumers, marking them dirty. It does not run any user code at this point. Reading a computed then checks whether it is dirty. If it is, it first checks whether any of its producers really changed (by version), and only re-runs the function when one did. This push of dirtiness plus pull of values is why computeds are lazy, cached, and glitch-free: a value that depends on two signals is never seen half-updated, because the recompute happens on read, after all writes.

Equality cuts the graph. If a computed recalculates and the new value is equal to the old (default check: Object.is), its version does not change, so its own consumers do not recalculate. In the example isEven is derived from a counter. A downstream label recomputes only when parity changes, not on every increment. You can supply a custom equal function in signal or computed options, for example to compare objects by id.

untracked(() => ...) reads signals without registering dependencies.

Rules and errors: a computed must be pure. Writing to a signal inside a computed throws an error (NG0600). Reading a signal that is currently being computed in a cycle throws too. Effects are scheduled asynchronously by Angular and run when the framework flushes them.

Consequences for design: keep computeds cheap and side-effect free, do not store derived data twice, and do not mutate objects held in signals (the default equality would see no change).

The script runs without a browser. It prints how many times each function really ran.

typescript
import { computed, signal, untracked } from '@angular/core';

// 1. Lazy and cached.
let doubledRuns = 0;
const count = signal(1);
const doubled = computed(() => {
  doubledRuns++;
  return count() * 2;
});
console.log('1. before first read, runs:', doubledRuns); // 0
doubled();
doubled();
console.log('1. after two reads, runs:', doubledRuns); // 1
count.set(2);
console.log('1. after set (still lazy), runs:', doubledRuns); // 1
console.log('1. value', doubled(), 'runs:', doubledRuns); // 4, 2

// 2. Equal results stop propagation.
let labelRuns = 0;
const isEven = computed(() => count() % 2 === 0);
const label = computed(() => {
  labelRuns++;
  return isEven() ? 'even' : 'odd';
});
label();
count.set(4);
label();
count.set(6);
console.log('2. label after 2 even changes:', label(), 'runs:', labelRuns); // even, 1
count.set(7);
console.log('2. label after odd:', label(), 'runs:', labelRuns); // odd, 2

// 3. Glitch-free diamond.
const price = signal(100);
const qty = signal(2);
const total = computed(() => price() * qty());
const tax = computed(() => total() * 0.1);
const bill = computed(() => `${total()} + ${tax()}`);
console.log('3.', bill()); // 200 + 20
price.set(200);
console.log('3.', bill()); // 400 + 40, never "400 + 20"

// 4. Dynamic dependencies.
const useFirst = signal(true);
const first = signal('A');
const second = signal('B');
let pickRuns = 0;
const picked = computed(() => {
  pickRuns++;
  return useFirst() ? first() : second();
});
picked();
second.set('B2'); // not a dependency yet
picked();
console.log('4. runs while second is ignored:', pickRuns); // 1
useFirst.set(false);
console.log('4.', picked(), 'runs:', pickRuns); // B2, 2

// 5. untracked and custom equality.
const trigger = signal(0);
const mixed = computed(() => trigger() + untracked(count));
console.log('5. mixed', mixed()); // 7
count.set(100);
console.log('5. untracked read ignored', mixed()); // 7
trigger.set(1);
console.log('5. after trigger', mixed()); // 101

const user = signal({ id: 1 }, { equal: (a, b) => a.id === b.id });
let userRuns = 0;
const userLabel = computed(() => {
  userRuns++;
  return `user ${user().id}`;
});
userLabel();
user.set({ id: 1 }); // new object, same id: treated as equal
userLabel();
console.log('5. runs with custom equal:', userRuns); // 1

Tested with Angular 20.3 under Node 22.18 or newer (`node main.ts`, package.json with `type: module`), twice with identical output. Run counts printed by the script are the point of the example.

Key points

  • Writes mark dependents dirty (push). Reads recompute stale values (pull). Nothing runs on write.
  • Dependencies are tracked on every run, so they can change dynamically.
  • A recomputed value equal to the old one stops propagation. Custom `equal` is possible.
  • Computed must be pure. Writing a signal in a computed throws NG0600.

Common mistakes

  • Putting a side effect inside `computed` and being surprised that it runs rarely, or not at all.
  • Mutating an object in a signal and expecting a change notification.
  • Assuming a computed re-runs on every `set` of its source. It runs lazily and only if the source really changed.

Follow-ups

  • What does glitch-free mean, and how does the pull model provide it?
  • How does a computed avoid recalculating when its source is set to the same value?
  • What happens if a computed reads itself?

Tips

  • Use the run counters from the script to explain laziness. A visible number is more convincing than a definition.
  • Mention versioning and equality, since they explain why the model is fast.
  • Connect the theory to a design rule: pure computeds, immutable values.

Evaluation rubric

  • Explains push dirtiness and pull evaluation.
  • Understands dynamic dependencies and equality cutting.
  • Lists the purity rules.