Sub topic 6
Computed, effect or event handler?
This chapter assumes you can write signal(), computed() and a basic effect(), and that you know how Angular components and templates work. It covers how to decide where a piece of logic belongs.
Three places for logic
A signal-based Angular component can react to change in three ways:
computed()derives a value from other signals.effect()runs a side effect whenever the signals it reads change.- An event handler runs once in response to something the user or the browser did.
Beginners often reach for effect() first because it "runs when things change". That is usually the wrong choice. Ask what the logic produces.
| Tool | Triggered by | Produces | Typical use |
|---|---|---|---|
| `computed()` | A read, when a dependency changed | A value | Totals, filtered lists, labels |
| `effect()` | A change in a signal it read | Nothing (a side effect) | Logging, storage, DOM or library calls |
| Event handler | A user or browser event | State changes, requests | Clicks, form submits, navigation |
Ask three questions
- Is the result a value you will read later? Use
computed(). It is lazy, cached, and always consistent with its inputs. - Is it a reaction to one specific action? Use an event handler. The action is the cause, so put the code where the action happens.
- Must something outside the signal graph follow the state continuously? Use
effect(). Examples arelocalStorage, analytics, a chart library or a canvas.
All three in one component
import { Component, signal, computed, effect } from '@angular/core';
@Component({
selector: 'app-cart',
template: `
<button (click)="add(5)">Add item</button>
<p>{{ count() }} items, total {{ total() }}</p>
`,
})
export class CartComponent {
prices = signal<number[]>([]);
// Derived state: computed
count = computed(() => this.prices().length);
total = computed(() => this.prices().reduce((sum, p) => sum + p, 0));
constructor() {
// Sync with an outside system: effect
effect(() => {
localStorage.setItem('cart', JSON.stringify(this.prices()));
});
}
// Response to a user action: event handler
add(price: number) {
this.prices.update((list) => [...list, price]);
console.log('item added');
}
}The console.log in add() belongs in the handler. If you moved it into an effect, it would also run once on creation and again whenever anything else changed prices, such as a code path that restores the cart. The handler logs only when the user clicks.
The common mistake: effects that derive state
This is the pattern to avoid:
import { signal, effect } from '@angular/core';
const firstName = signal('Ada');
const lastName = signal('Lovelace');
const fullName = signal('');
// Avoid: copying one signal into another with an effect
effect(() => {
fullName.set(`${firstName()} ${lastName()}`);
});It has several problems:
fullNameis empty until the effect first runs, so a read right after creation can see a stale value.- Effects are scheduled, not synchronous, so
fullNamecan lag behind its inputs. - Writing signals inside effects makes the data flow hard to follow. Recent Angular versions allow it by default, but the guidance is still to avoid it.
- The value is writable from anywhere, so any code can break the relationship.
The computed() version fixes all four:
import { signal, computed, effect } from '@angular/core';
const firstName = signal('Ada');
const lastName = signal('Lovelace');
const fullName = computed(() => `${firstName()} ${lastName()}`);
// The effect only reports the result to the outside world
effect(() => console.log('Full name is', fullName()));Here fullName is read-only, always consistent, and only recalculated when someone reads it after a dependency changed.
Edge cases in the decision
- A request after a click. Start the request in the handler. Do not put the click in a signal and fire the request from an effect. That hides the cause behind a scheduling step.
- A request that depends on an input. If the request must re-run whenever
id()changes, an effect with cleanup (see the next chapter) or a resource-style API fits better than a handler, because no single event is the cause. - Derived state that the user can also overwrite. Neither
computed()nor an effect fits. That is the case forlinkedSignal(), covered later in this tutorial.
<br>
Exercise
A component has a items signal and a selectedId signal. You need (a) the currently selected item for the template, (b) a call to an analytics library each time the selection changes, and (c) a server request when the user presses "Delete". Which tool fits each?
Show answer
(a) computed(), because it derives a value from items and selectedId. (b) effect(), because it syncs with an outside system whenever selectedId changes. (c) An event handler, because the user's click is the cause and the request should run once per click, not when a signal changes.