Sub topic 6
Computed, effect or event handler?
This chapter assumes you know TypeScript, Angular components and templates, dependency injection, and the basics of writable signals (signal(), set(), update()). It also assumes you have read the earlier chapters on computed() and effect(). Here you will learn how to decide where a piece of logic belongs.
The decision in one question
Angular gives you three places to put logic that reacts to something. Each answers a different question.
| Tool | Question it answers | Runs when | Produces |
|---|---|---|---|
| `computed()` | "What is this value, given other signals?" | A consumer reads it and a dependency has changed | A read-only value |
| `effect()` | "What must happen outside the signal graph whenever these signals change?" | After a dependency changes, during change detection | Nothing (a side effect) |
| Event handler | "What should happen because the user or the browser did something?" | When the event fires | Writes to signals, calls services |
Most mistakes in signal code come from using the wrong tool. A typical one is an effect that copies one signal into another. The sections below give a rule for each tool and then show the failures that appear when the rules are broken.
Use `computed()` for derived values
If a value can be calculated from other signals, make it a computed(). You get three things for free. The value is lazy, so it is only calculated when something reads it. It is cached, so repeated reads cost nothing until a dependency changes. It is always consistent with its sources, because nobody can write to it and leave it stale.
import { signal, computed, effect } from '@angular/core';
const firstName = signal('Ada');
const lastName = signal('Lovelace');
// Prefer: derived state as a computed signal
const fullName = computed(() => `${firstName()} ${lastName()}`);
// Reserve effects for side effects such as logging or syncing to an outside system
effect(() => console.log('Full name is', fullName()));Here fullName is the derived state. The effect does not compute anything. It only reports the result to the console, which is outside the signal graph.
Treat these as signs that something should be a computed():
- The code reads signals and returns a value.
- You will show the value in a template or use it in another computed.
- You would otherwise write "whenever A or B changes, update C".
A computed function should be pure. It should not write to signals, make HTTP calls, or change objects it did not create. Angular forbids writing to a signal inside a computed() and throws an error if you try.
Use `effect()` for side effects
An effect is for work that leaves the signal graph. The usual cases are:
- Writing to
localStorageorsessionStorage. - Logging or sending analytics.
- Calling an imperative API, such as a chart library, a canvas, or a third-party widget.
- Keeping a DOM property in sync when no template binding can express it.
The effect from the earlier chapter shows the pattern. It reads signals, and the work happens outside Angular's state.
import { Component, signal, computed, effect } from '@angular/core';
@Component({
selector: 'app-counter',
template: `<button (click)="increment()">{{ count() }} (x2 = {{ doubled() }})</button>`,
})
export class CounterComponent {
count = signal(0);
doubled = computed(() => this.count() * 2);
constructor() {
effect(() => {
console.log(`count=${this.count()}, doubled=${this.doubled()}`);
});
}
increment() {
this.count.update((c) => c + 1);
}
}Note the split of responsibilities. doubled is a value, so it is a computed(). The log line is a side effect, so it lives in an effect(). The click is an event, so increment() is a handler that writes to a signal.
Effects have timing rules that make them a poor fit for anything that other code depends on:
- An effect runs at least once after it is created.
- It runs asynchronously, as part of change detection, not at the moment a signal is set. Several writes in a row usually produce one run.
- It has no return value, so nothing can read its result.
Because of the timing, code that depends on an effect having already run is fragile. If the result matters to a template or to other logic, it belongs in a computed().
Use an event handler for actions
An event handler responds to something that happened: a click, a form submit, a route change, a message from a WebSocket. The handler knows what happened, and that matters. When the user presses "Save", you know you should save. When a signal merely holds a certain value, you do not know why it has that value.
A reliable rule: if the logic is a response to a specific user action, put it in the handler for that action, even if the action changes signals that an effect could also observe.
import { Component, signal } from '@angular/core';
@Component({
selector: 'app-profile-form',
template: `
<input [value]="name()" (input)="onInput($event)" />
<button (click)="save()">Save</button>
`,
})
export class ProfileFormComponent {
name = signal('');
onInput(event: Event) {
this.name.set((event.target as HTMLInputElement).value);
}
save() {
// The user asked for this. It belongs here, not in an effect.
console.log('saving', this.name());
}
}If you moved save() into an effect that watches name(), the app would save on every keystroke. It would also save once when the component is created. The handler avoids both problems because it runs only when the user clicks.
Failure modes when the wrong tool is used
Copying signals with an effect
This is the most common error. An effect reads one signal and writes another, so the second signal is derived state in disguise.
import { Component, signal, effect } from '@angular/core';
@Component({
selector: 'app-bad-total',
template: `{{ total() }}`,
})
export class BadTotalComponent {
price = signal(10);
quantity = signal(2);
total = signal(0);
constructor() {
// Anti-pattern: derived state kept in sync by an effect
effect(
() => {
this.total.set(this.price() * this.quantity());
},
{ allowSignalWrites: true },
);
}
}The problems are concrete:
totalis wrong between the momentpricechanges and the moment the effect runs.- Anyone can call
total.set()and break the relationship. - Angular blocks signal writes in effects by default. The
allowSignalWritesoption exists to opt out, and needing it is a signal that the design is wrong. Recent Angular versions relax this restriction, but the guidance does not change. - Writes inside effects can trigger other effects, which makes the order of updates hard to follow and can create loops.
The fix is a one-line computed():
import { signal, computed } from '@angular/core';
const price = signal(10);
const quantity = signal(2);
const total = computed(() => price() * quantity());Doing user-driven work in an effect
Suppose you want to load data when the user picks a category. An effect that watches category() and calls the API looks tidy. It also runs once on creation, runs again if anything else it reads changes, and gives you no easy way to say "only when the user chose this". If the trigger is a user action, call the API from the handler. If the trigger is genuinely "this input changed" and you need an async result, a resource-style API or the RxJS interop at the end of this tutorial usually fits better than a hand-written effect.
Putting side effects inside `computed()`
A computed may run once, many times, or not at all. That depends on who reads it and whether its dependencies change. A console.log or an HTTP call inside it will therefore fire at unpredictable moments. Keep it pure and move the action to an effect or a handler.
Edge cases to keep in mind
- Effects track whatever they read. If an effect calls a method that reads other signals, those become dependencies too. A later chapter shows how
untracked()limits this. - Effects are tied to a lifetime. An effect created in a component is destroyed with it. The next chapter covers injection context and cleanup.
- An effect that never reads a signal never re-runs. It runs once and stops, which is rarely what you want.
- Computed values do not run without a reader. If you need something to happen even when nothing reads the value, that is an effect's job, not a computed's.
Applying the rules to a realistic case
Consider a product list with a text filter and a "Save filter" button. The page should show the filtered items, show the number of matches, and remember the saved filter.
import { Component, signal, computed, effect } from '@angular/core';
interface Product { id: number; name: string; }
@Component({
selector: 'app-product-list',
template: `
<input [value]="filter()" (input)="onFilter($event)" />
<button (click)="saveFilter()">Save filter</button>
<p>{{ count() }} matches</p>
<ul>
@for (p of visible(); track p.id) {
<li>{{ p.name }}</li>
}
</ul>
`,
})
export class ProductListComponent {
products = signal<Product[]>([
{ id: 1, name: 'Keyboard' },
{ id: 2, name: 'Mouse' },
{ id: 3, name: 'Monitor' },
]);
filter = signal('');
// Derived values: computed
visible = computed(() => {
const f = this.filter().toLowerCase();
return this.products().filter((p) => p.name.toLowerCase().includes(f));
});
count = computed(() => this.visible().length);
constructor() {
// Outside system, runs when the filter changes: effect
effect(() => {
document.title = `Products (${this.count()})`;
});
}
// User action: event handlers
onFilter(event: Event) {
this.filter.set((event.target as HTMLInputElement).value);
}
saveFilter() {
localStorage.setItem('productFilter', this.filter());
}
}Each piece lands in the right place:
visibleandcountare values, so they arecomputed().- Setting
document.titlepushes state to the browser, outside the signal graph, so it is aneffect(). - Saving the filter is something the user asked for, so it is in the
saveFilter()handler. An effect here would write to storage on every keystroke.
Summary of the rules
- Can it be calculated from signals? Use
computed(). - Does it push state to something Angular does not manage? Use
effect(). - Does it answer a specific action? Use an event handler.
- Does an effect only write to another signal? Replace it with
computed(), or withlinkedSignal()when the value must also be writable, as the later chapter explains.
Exercise
A component has items = signal<number[]>([]) and an effect that reads items() and calls this.itemCount.set(items().length), where itemCount is a writable signal shown in the template. What is wrong with this design, and how would you rewrite it?
Show answer
itemCount is derived state kept in sync by an effect. It is stale between the change to items and the effect run, and anyone can overwrite it with set(). Replace both with itemCount = computed(() => this.items().length). The template reads itemCount() as before, and the effect is no longer needed.
Exercise
A "Delete account" button must call accountService.delete() once, only when the user confirms. A colleague proposes an effect that watches a confirmed signal and calls the service. Which tool would you use instead, and why?
Show answer
Use an event handler, such as onConfirm(), that calls accountService.delete(). The action is a response to a specific user decision. An effect would also run once when it is created, and it would run again if any other signal it reads changed, so the delete could fire at the wrong time. The handler runs only when the user acts.