Angular 12: computed() Deep Dive — Chaining & Purity
easy⏱ 5 mincourseangular
Chained computed signals build a dependency graph
total = computed(() => subtotal() + tax()) reads two OTHER computed signals — Angular tracks that total depends (transitively) on items, and re-evaluates subtotal, then tax, then total, only when items actually changes, and only once per change, no matter how many components read total.
subtotal = computed(() => this.items().reduce((sum, i) => sum + i.price * i.qty, 0));
tax = computed(() => this.subtotal() * 0.08);
total = computed(() => this.subtotal() + this.tax());
computed() callbacks must be pure
Never write to another signal, call an API, or mutate external state inside a computed(). It may run multiple times, be skipped, or run lazily (only when read) — side effects inside it are unpredictable and unsupported. If you need a side effect in reaction to a signal, that's exactly what effect() (lesson 13) is for.
// ANTI-PATTERN — never do this inside computed():
total = computed(() => {
const t = this.subtotal() + this.tax();
this.lastTotal.set(t); // writing to a signal inside computed() is unsupported
return t;
});