Sub topic 3
Why computed values are lazy and cached
This chapter assumes you know basic TypeScript, how Angular components and templates work, and how to create and update a writable signal with signal(), set() and update(). It also assumes you have seen computed() once. Here you will learn what happens inside a computed signal between the moment you create it and the moment you read it.
The two properties: lazy and memoized
A computed signal has two behaviors that explain most of what you will observe in practice.
- Lazy. The derivation function does not run when you call
computed(). It runs the first time something reads the signal. - Memoized. After the function runs, Angular stores the result. Later reads return the stored value without calling the function again, until one of the signals the function read has changed.
Together these mean a computed signal does work only when its value is needed and only when its inputs have changed.
import { signal, computed } from '@angular/core';
const price = signal(10);
const quantity = signal(2);
const total = computed(() => {
console.log('computing total');
return price() * quantity();
});
console.log('created'); // "computing total" has NOT been printed yet
console.log(total()); // prints "computing total", then 20
console.log(total()); // prints 20 only, the cached value is reused
quantity.set(3); // nothing is printed here
console.log(total()); // prints "computing total", then 30Notice that quantity.set(3) prints nothing. Setting a signal does not recompute the computed signals that depend on it. It only marks them as possibly out of date. The recomputation happens at the next read.
What the cache stores
Each computed signal holds three things:
- The last value it produced.
- The list of signals it read during that run, which are its dependencies.
- A record of whether any of those dependencies has changed since the value was produced.
A read follows this path:
The check on the "Did any dependency change" branch is cheap. It compares version information, so it does not re-run your code.
Laziness in practice
Because a computed signal runs only when read, an unused computed signal costs almost nothing. You can declare several derived values on a component and pay only for the ones the template or other code actually reads.
import { Component, signal, computed } from '@angular/core';
@Component({
selector: 'app-report',
template: `
@if (expanded()) {
<p>{{ summary() }}</p>
}
<button (click)="expanded.set(!expanded())">Toggle</button>
`,
})
export class ReportComponent {
expanded = signal(false);
rows = signal<number[]>([4, 8, 15, 16, 23, 42]);
summary = computed(() => {
console.log('building summary');
return this.rows().reduce((sum, n) => sum + n, 0);
});
}While expanded() is false, the template never reads summary(), so "building summary" is never logged, even if rows changes many times. When the user opens the section, the template reads summary() for the first time and the function runs once.
Laziness also means that side effects inside a derivation function are unreliable. You cannot know when, or how often, the function will run. Keep derivation functions pure: they should read signals and return a value, and nothing else.
Memoization and repeated reads
Memoization matters when the derivation is expensive or when many consumers read the same value. Suppose a template reads visibleRows() in three places. Without caching, you would filter the list three times per render. With a computed signal, the filter runs once and the other two reads return the stored array.
import { signal, computed } from '@angular/core';
const rows = signal([5, 12, 7, 30, 2]);
const minimum = signal(6);
const visibleRows = computed(() => {
console.log('filtering');
return rows().filter((n) => n >= minimum());
});
visibleRows(); // "filtering"
visibleRows(); // cached
visibleRows(); // cached
minimum.set(10);
visibleRows(); // "filtering" again, because minimum changedThe cache is keyed to the dependencies, not to time or to the number of reads. A value can stay cached for as long as its dependencies do not change.
When a change does not cause recomputation
A dependency counts as changed only if it is set to a value that is different from the current one. Signals compare values with Object.is by default. Setting a signal to the same primitive value is not a change.
import { signal, computed } from '@angular/core';
const count = signal(1);
const label = computed(() => {
console.log('label computed');
return `Count: ${count()}`;
});
label(); // "label computed"
count.set(1); // same value, so no change is recorded
label(); // cached, nothing is loggedObjects and arrays are compared by reference. Calling items.set([...items()]) creates a new array, so the signal does record a change even though the contents match. The same rule applies to a computed signal's own result, which comes up next.
Equality of the result and downstream work
A computed signal is itself a dependency of other computed signals, effects and templates. When it recomputes, Angular compares the new result with the old one using the same Object.is check. If the two are equal, consumers of the computed signal are not told that it changed, and they do not need to recompute.
import { signal, computed } from '@angular/core';
const temperature = signal(21.4);
const isFreezing = computed(() => temperature() <= 0);
const advice = computed(() => {
console.log('advice computed');
return isFreezing() ? 'Wear a coat' : 'No coat needed';
});
advice(); // "advice computed"
temperature.set(22.9); // temperature changed, isFreezing will recompute...
advice(); // ...but isFreezing is still false, so advice is NOT recomputedHere isFreezing recomputes when advice is read, because temperature changed. Its result is still false, so advice keeps its cached value. A chain of small computed signals therefore limits how far a change spreads. Splitting a large derivation into stages is sometimes worthwhile for this reason, but only when the intermediate value is a primitive or otherwise stable. Later in this tutorial you will see how a custom equal function handles array and object results.
Read-only and no writes
A computed signal is read-only. It has no set() or update() method, and TypeScript will reject a call to either. Its value always comes from its derivation function.
Angular also forbids writing to a signal from inside a derivation function. If you try, Angular throws an error at run time. This protects the model: a derivation that changed state while being read would make results depend on read order.
import { signal, computed } from '@angular/core';
const a = signal(1);
const b = signal(0);
const bad = computed(() => {
b.set(a() * 2); // Error: writing to signals is not allowed in a computed
return a();
});
bad();If you find yourself wanting to write a signal from a derivation, the value you want is probably another computed signal, or you need an effect or an event handler. Chapter material later in this tutorial covers that choice.
Circular dependencies
Because a computed signal runs on read, a cycle cannot settle. If a reads b and b reads a, reading either one triggers the other, and Angular detects the loop and throws a "Detected cycle in computations" error.
import { computed } from '@angular/core';
const a = computed((): number => b() + 1);
const b = computed((): number => a() + 1);
a(); // throws: Detected cycle in computations.The fix is to restructure the data so that each value depends on inputs that sit lower in the graph, never on a value that depends back on it.
Common errors
- Expecting a computed signal to run when created. It does not. If you put a
console.login it to confirm it ran, no output appears until a read. - Relying on side effects in the derivation. Logging, network calls and writes inside
computed()may run at unexpected times, or not at all. Move them to an effect or an event handler. - Mutating an array or object in place.
items().push(4)changes the contents but not the reference, so the signal records no change and computed signals that read it keep returning stale values. Useitems.update((list) => [...list, 4])instead. - Reading a signal only on some paths and assuming it is always tracked. Only signals read during the latest run are dependencies. The next chapter section covers this in detail.
- Calling a computed signal without parentheses.
totalis the signal function.total()is its value. In a template,{{ total }}prints the function, not the number.
Summary of the model
| Property | What it means | Consequence |
|---|---|---|
| Lazy | The function runs on the first read, not at creation | Unused computed signals cost nothing |
| Memoized | The result is stored until a dependency changes | Repeated reads are cheap |
| Dependency-tracked | Signals read during a run become dependencies | Only relevant changes cause recomputation |
| Result equality | An equal result does not notify consumers | Changes stop spreading early |
| Read-only and pure | No writes, no reliance on side effects | Results do not depend on read order |
Exercise
A component declares doubled = computed(() => { console.log('run'); return this.count() * 2; }). The template does not read doubled(). The code calls count.set(5) three times in a row, then the user opens a panel whose template reads doubled() twice. How many times is "run" logged, and why?
Show answer
Once. The function does not run at creation or when count is set, because a computed signal is lazy and each set only marks it as possibly stale. The first read in the panel runs the function and stores the result. The second read finds no dependency change since that run and returns the cached value.
Exercise
Given const n = signal(3); const isEven = computed(() => n() % 2 === 0); const message = computed(() => { console.log('message'); return isEven() ? 'even' : 'odd'; });, you read message(), then call n.set(5), then read message() again. Is "message" logged the second time? Explain.
Show answer
No. After n.set(5), reading message() first checks isEven, which recomputes and still returns false. Because the new result equals the old one under Object.is, message is not notified of a change, so it returns its cached value without running its function.