TExcelTAD
Home › Angular › computed() & effect()

computed() & effect()

Writable signals hold state. Two more functions build on them:

  • computed() derives a new read-only signal from other signals — like a spreadsheet formula.
  • effect() runs a side effect (logging, saving to storage, calling a non-Angular library) whenever the signals it reads change.

Both track their dependencies automatically: whatever signals they read while running become their dependencies.

computed()

angular · try it yourself
import { Component, computed, signal } from '@angular/core';

interface Line { name: string; price: number; qty: number; }

@Component({
  selector: 'app-cart',
  template: `
    @for (l of lines(); track l.name) {
      <p>{{ l.qty }} × {{ l.name }} — {{ l.price * l.qty }} USD</p>
    }
    <hr />
    <p>Items: {{ itemCount() }}</p>
    <p>Total: <strong>{{ total() }} USD</strong>
      @if (freeShipping()) { <span>🚚 free shipping</span> }
    </p>
    <button (click)="addMug()">Add a mug (8 USD)</button>
  `,
})
export class Cart {
  lines = signal<Line[]>([
    { name: 'Notebook', price: 6, qty: 3 },
    { name: 'Pen set', price: 12, qty: 1 },
  ]);

  itemCount = computed(() => this.lines().reduce((n, l) => n + l.qty, 0));
  total = computed(() => this.lines().reduce((s, l) => s + l.price * l.qty, 0));
  freeShipping = computed(() => this.total() >= 30);

  addMug() {
    this.lines.update((ls) => [...ls, { name: 'Mug', price: 8, qty: 1 }]);
  }
}

Computed signals are:

  • Lazy — the function only runs when someone reads the value.
  • Memoised — the result is cached until a dependency changes.
  • Read-only — you cannot set() a computed signal.
  • Chainable — freeShipping depends on total, which depends on lines.

How automatic tracking works

The trick behind computed and effect: while a reactive function runs, a global "current observer" is set. Every signal read during that time registers the observer as a dependent. Here is a compact, working version in plain TypeScript:

ts · try it yourself
type Observer = () => void;
let current: Observer | null = null;

function signal<T>(initial: T) {
  let value = initial;
  const observers = new Set<Observer>();
  const read = () => {
    if (current) observers.add(current);
    return value;
  };
  const set = (next: T) => {
    if (Object.is(next, value)) return;
    value = next;
    [...observers].forEach((o) => o());
  };
  return { read, set };
}

function effect(fn: () => void) {
  const run = () => {
    const prev = current;
    current = run;
    try { fn(); } finally { current = prev; }
  };
  run();
}

const price = signal(10);
const qty = signal(2);

effect(() => console.log(`total = ${price.read() * qty.read()}`));
qty.set(3);
price.set(12);
price.set(12); // unchanged, no re-run
total = 20
total = 30
total = 36

Angular's implementation adds a lot on top — glitch-free batching, lazy computeds, cleanup — but the dependency-tracking idea is the same.

effect()

Use effect() to synchronise signal state with something outside Angular's templates. Effects must be created in an injection context, typically the constructor or a field initializer:

angular · try it yourself
import { Component, effect, signal } from '@angular/core';

@Component({
  selector: 'app-notes',
  template: `
    <textarea rows="3" [value]="draft()" (input)="draft.set($any($event.target).value)"></textarea>
    <p><small>{{ draft().length }} characters · autosaved</small></p>
  `,
})
export class Notes {
  draft = signal(localStorage.getItem('draft') ?? 'Buy milk');

  constructor() {
    effect(() => {
      const text = this.draft();
      localStorage.setItem('draft', text);
      console.log('saved:', text);
    });
  }
}
saved: Buy milk

Effects always run at least once, then again (asynchronously, during change detection) whenever a signal they read changes. They are cleaned up automatically when the component is destroyed.

Don't use effect() to derive state

A common mistake is copying one signal into another inside an effect. Use computed() instead — it's synchronous, can't get out of sync and never causes extra render passes:

❌ Avoid ✅ Prefer
effect(() => this.total.set(this.a() + this.b())) total = computed(() => this.a() + this.b())

linkedSignal: derived but writable

Sometimes a value should default to something derived but still be editable — for example, the selected option resets when the list of options changes. linkedSignal covers that:

ts
options = signal(['S', 'M', 'L']);
selected = linkedSignal(() => this.options()[0]); // 'S', can be set by the user
// selected.set('L')  → 'L'
// options.set(['XL', 'XXL'])  → selected resets to 'XL'

Tip: Rule of thumb — computed for values, effect for actions in the outside world, linkedSignal for "editable default".

Test yourself

When does a computed() signal recompute its value?

  1. Every second
  2. On every change detection cycle
  3. When it is read after one of its dependencies changed
  4. Only when you call .refresh()

Which is the right tool for keeping fullName in sync with first and last signals?

  1. An effect that calls fullName.set(...)
  2. computed(() => this.first() + ' ' + this.last())
  3. A setTimeout loop
  4. ngOnChanges

Where can you call effect() without extra options?

  1. Anywhere, even in a plain function after startup
  2. Inside an injection context such as a component constructor
  3. Only in main.ts
  4. Only in templates