Sub topic 3
Why computed values are lazy and cached
This chapter assumes you can write a writable signal with signal(), set() and update(), and that you have seen computed() return a read-only derived value. Here you will learn when a computed function actually runs and when Angular skips it.
Two rules: compute on read, reuse until stale
A computed signal follows two rules:
- Lazy: its function does not run when you create it. It runs the first time something reads it.
- Memoized: after it runs, Angular stores the result. Later reads return the stored value until a dependency changes.
The example below logs inside the computed function so you can see each run.
import { signal, computed } from '@angular/core';
const price = signal(10);
const quantity = signal(2);
const total = computed(() => {
console.log('computing total');
return price() * quantity();
});
quantity.set(5); // nothing logged: total has never been read
console.log(total()); // logs 'computing total', then 50
console.log(total()); // 50 only: the cached value is reused
price.set(20); // nothing logged: total is only marked stale
console.log(total()); // logs 'computing total', then 100The function ran twice, not four times. Writing to quantity before the first read cost nothing. The second read used the cache. Writing to price did not recompute anything. It only flagged total as out of date.
The life of a computed value
A computed signal is always in one of three situations, and a write or a read moves it between them.
Notice that nothing leads from Stale to a rerun without a read. Ten writes to quantity in a row still cause at most one recomputation, and only if someone reads total afterwards.
Why Angular designs it this way
Laziness and caching solve three practical problems:
- No wasted work. A computed that nothing reads never runs. If it sits behind an
@ifthat is currently false, its cost is zero. - No repeated work. A template can read
total()in five places during one change detection pass. The function runs once, and the other four reads hit the cache. - No glitches. Because values are pulled on demand, you never read a half-updated state. After
price.set(20)andquantity.set(3), the next read oftotal()sees both new values, never a mix of old and new.
Stale does not always mean changed
When a dependency changes, Angular marks the computed stale, but a stale value is not necessarily a different one. On the next read the function reruns and the new result is compared with the old one using Object.is. If they are equal, the computed keeps its value and tells its own consumers nothing changed. Anything that depends on it, such as another computed or an effect, then does not rerun.
import { signal, computed } from '@angular/core';
const count = signal(3);
const isEven = computed(() => count() % 2 === 0);
const message = computed(() => {
console.log('building message');
return isEven() ? 'even' : 'odd';
});
console.log(message()); // logs 'building message', then 'odd'
count.set(5); // isEven becomes stale
console.log(message()); // 'odd' (isEven recomputed to false again, so message is reused)The second read of message() prints no log. isEven reran, produced false again, and so message kept its cached value.
Objects and arrays are different. A new array is never Object.is-equal to the old one, even with the same contents. A computed that returns items().filter(...) therefore looks changed after every recomputation. A later chapter shows how a custom equal function fixes this.
Common mistakes
- Expecting a computed to run on creation. If you put a
console.login one to "check it works" and see nothing, it is not broken. Nothing has read it yet. - Relying on the function running. Code that depends on a computed running (to start a timer, for example) will fail, since the function may be skipped or reused from cache.
- Mutating in place. If a writable signal holds an array and you call
pushon it, no write is registered, so the computed never goes stale. Useset()orupdate()with a new array. - Reading inside a computed expecting cheap repeats. The cache holds only while no dependency changes. A function that depends on a frequently changing signal recomputes on nearly every read.
Exercise
In the code below, how many times is 'running' logged, and why? const a = signal(1); const doubled = computed(() => { console.log('running'); return a() * 2; }); a.set(2); a.set(3); console.log(doubled()); console.log(doubled());
Show answer
It is logged once. The computed is lazy, so the two writes to a run nothing. The first doubled() read runs the function and gets 6. The second read finds no dependency changes since then and returns the cached 6.
Exercise
A computed returns isEven(), which reruns whenever count changes. count goes from 3 to 5, then you read the computed that depends on isEven. Does that downstream computed rerun? Explain.
Show answer
No. isEven is stale after the write, but when it reruns it returns false again. The result is Object.is-equal to the cached value, so the downstream computed is not notified and keeps its cached result.