Sub topic 3
Deriving State with computed()
A component's state often contains values that can be worked out from other values: a cart total, a filtered list, or a flag saying whether a form is valid. If you store these as separate writable signals, you have to keep them in sync by hand, and sooner or later they drift apart. computed() lets you state the relationship once. Angular then keeps the derived value correct, recalculates it only when needed, and caches the result between reads.
This chapter assumes you know TypeScript generics and arrow functions, you can build Angular components with templates, and you have read the previous chapter on writable signals (signal(), set(), update()).
The basic shape
A computed signal wraps a derivation function. Any signal you read inside that function becomes a dependency. The result is a read-only signal that you call like a function, the same way you read a writable signal.
import { Component, computed, signal } from '@angular/core';
@Component({
selector: 'app-counter',
template: `
<p>Count: {{ count() }} (double: {{ double() }})</p>
<button (click)="increment()">+1</button>
<button (click)="reset()">Reset</button>
`,
})
export class CounterComponent {
count = signal(0);
double = computed(() => this.count() * 2);
increment() {
this.count.update(c => c + 1);
}
reset() {
this.count.set(0);
}
}You never list dependencies yourself. When double's function runs, Angular records that it called this.count(). When count changes, double is marked stale. Its type is Signal<number>, not WritableSignal<number>, so it has no set() or update() method. The only way to change a derived value is to change what it derives from.
Memoization and lazy evaluation
Computed signals have two properties that matter for performance and for reasoning about your code.
- Memoized: after the function runs, the result is cached. Reading the signal again returns the cached value without running the function, until a dependency changes.
- Lazy: the function does not run when the computed signal is created, and it does not run when a dependency changes. It runs only when someone reads the signal and the cached value is missing or stale.
You can see both properties with a counter on the derivation function. Signals work outside components, so this runs as a plain script in any project that has @angular/core installed.
import { computed, signal } from '@angular/core';
const price = signal(20);
const qty = signal(3);
let runs = 0;
const total = computed(() => {
runs++;
return price() * qty();
});
console.log(runs); // 0 -> creating the computed ran nothing
console.log(total()); // 60 -> first read runs the function
console.log(total()); // 60 -> cached, no run
console.log(runs); // 1
price.set(25);
qty.set(4);
console.log(runs); // 1 -> two changes, still no run
console.log(total()); // 100 -> one recomputation covers both changes
console.log(runs); // 2Laziness means that setting several dependencies in a row costs one recomputation, not one per change. It also means that an expensive computed signal that nothing reads never costs anything. A filtered list behind a closed panel stays dormant until the panel opens.
The lifecycle of a single computed signal looks like this:
Dependencies are dynamic
Angular re-records the dependency set on every run. Only the signals actually read during the latest run count. This matters when the function contains branches.
import { computed, signal } from '@angular/core';
const showDetails = signal(false);
const details = signal('Ships in 2 days');
let runs = 0;
const panel = computed(() => {
runs++;
return showDetails() ? details() : 'Details hidden';
});
console.log(panel()); // 'Details hidden'
details.set('Ships today');
console.log(panel()); // 'Details hidden', and runs is still 1
showDetails.set(true);
console.log(panel()); // 'Ships today', runs is 2
details.set('Out of stock');
console.log(panel()); // 'Out of stock', runs is 3While showDetails is false, the function never calls details(), so details is not a dependency and changing it does nothing. Once the branch flips, details joins the dependency set. This is usually what you want, and it is cheaper than static dependency lists. It also means a signal read behind a short-circuit (a() && b()) or an early return is tracked only when that code path actually executes.
Equality stops changes from spreading
When a stale computed signal recalculates, Angular compares the new result with the old one using Object.is by default. If they are equal, the computed signal counts as unchanged, and anything that depends on it is not recalculated.
import { computed, signal } from '@angular/core';
const count = signal(0);
const isEven = computed(() => count() % 2 === 0);
let labelRuns = 0;
const label = computed(() => {
labelRuns++;
return isEven() ? 'even' : 'odd';
});
console.log(label()); // 'even', labelRuns is 1
count.set(2);
console.log(label()); // 'even', labelRuns is still 1
count.set(3);
console.log(label()); // 'odd', labelRuns is 2When count goes from 0 to 2, isEven recalculates but still returns true, so label keeps its cache. Chains of small computed signals therefore stop work early. A later chapter covers custom equality functions, which let you change what "unchanged" means.
computed() compared with the alternatives
| Approach | Recalculates | Cached | Reactive in templates | Typical use |
|---|---|---|---|---|
| `computed(() => ...)` | On read, only if a dependency changed | Yes | Yes | Any value derived from signals |
| Getter `get total() {...}` | On every read | No | Only when change detection runs | Cheap derivations from plain fields |
| Template expression `{{ a() * b() }}` | Every change detection pass | No | Yes | Trivial one-off arithmetic |
| Extra `signal()` synced by hand or by `effect()` | Whenever your code remembers | N/A | Yes | Avoid this for derived state |
Copying derived values into a writable signal with an effect is the most common anti-pattern. It adds a delay, it can render an inconsistent intermediate state, and it repeats something computed() does for you. If the value can be calculated from other signals, use computed(). If the user must also be able to override it, the linkedSignal() chapter covers that case.
Rules for the derivation function
Treat the function as a pure calculation: it reads signals and returns a value.
Do not write to signals
Calling set() or update() inside a computed function throws NG0600: Writing to signals is not allowed in a computed. Writes belong in event handlers, service methods, or, for real side effects, in effect().
Do not do async work
computed() returns whatever the function returns synchronously. If you return a Promise, the signal's value is the promise object, and signals read after an await are not tracked. For async data, use RxJS interop or the resource() API, both covered later.
Only signal reads are tracked
Reading a plain class field or a localStorage entry inside a computed function works once, but changes to it never mark the computed stale.
import { computed, signal } from '@angular/core';
class Pricing {
taxRate = 0.2; // plain field: not tracked
net = signal(100);
gross = computed(() => this.net() * (1 + this.taxRate));
}
const p = new Pricing();
console.log(p.gross()); // 120
p.taxRate = 0.1;
console.log(p.gross()); // still 120: the cache was never invalidatedThe fix is to make taxRate a signal.
Replace, do not mutate
If a computed signal depends on items = signal<string[]>([]) and you call items().push('x'), the array reference is unchanged. Object.is sees no change, nothing becomes stale, and the computed keeps returning its old result. Use items.update(list => [...list, 'x']) instead.
Create computed signals once
Declare computed signals as class fields or in a constructor. A computed created inside a method that the template calls on every check is a new signal each time, with an empty cache, so you lose memoization and gain allocation churn.
A worked example: filtering and summarizing a list
import { Component, computed, signal } from '@angular/core';
interface Task { id: number; title: string; done: boolean; }
@Component({
selector: 'app-tasks',
template: `
<input [value]="filter()" (input)="filter.set($any($event.target).value)" />
<p>{{ remaining() }} of {{ tasks().length }} left</p>
@for (task of visible(); track task.id) {
<label>
<input type="checkbox" [checked]="task.done" (change)="toggle(task.id)" />
{{ task.title }}
</label>
}
`,
})
export class TasksComponent {
tasks = signal<Task[]>([
{ id: 1, title: 'Write tests', done: false },
{ id: 2, title: 'Review PR', done: true },
{ id: 3, title: 'Write docs', done: false },
]);
filter = signal('');
visible = computed(() => {
const term = this.filter().trim().toLowerCase();
return term
? this.tasks().filter(t => t.title.toLowerCase().includes(term))
: this.tasks();
});
remaining = computed(() => this.tasks().filter(t => !t.done).length);
toggle(id: number) {
this.tasks.update(list =>
list.map(t => (t.id === id ? { ...t, done: !t.done } : t))
);
}
}Typing in the box changes filter, so only visible recalculates, because remaining does not read filter. Toggling a task replaces the array, so both computed signals become stale and each recalculates once when the template reads it.
Exercise
A computed signal is defined as const summary = computed(() => user().name + ' (' + cart().length + ')'). Your code calls user.set(...) three times and cart.update(...) twice, and only then reads summary(). How many times does the derivation function run between those writes and the read, and why?
Show answer
It runs once, at the read. Computed signals are lazy: writes only mark the signal stale and never trigger a run. The first read after the writes recalculates once using the latest values.
Exercise
In const badge = computed(() => isAdmin() || hasPermission()), isAdmin() currently returns true. A test changes hasPermission and expects badge to recalculate, but it doesn't. Explain why, and say whether this is a bug.
Show answer
The || short-circuits, so hasPermission() is never called while isAdmin() is true. It is therefore not in the current dependency set, and changing it doesn't mark badge stale. This is correct behavior: the result can't change until isAdmin becomes false, and at that point the next run reads hasPermission and starts tracking it.
Exercise
A teammate writes discounted = computed(() => { const v = this.price() * 0.9; this.lastDiscount.set(v); return v; }). What happens, and how should it be restructured?
Show answer
Writing to lastDiscount inside a computed throws NG0600. Keep discounted pure (computed(() => this.price() * 0.9)) and read discounted() wherever lastDiscount was used. If a side effect such as logging or persistence is really needed, put it in an effect() that reads discounted().