Computed signals in Angular(v21)

While Writable Signals are the “storage units” of your application, Computed Signals are the “brains.”

Think of a spreadsheet: a Writable Signal is a cell where you type a number (like A1), and a Computed Signal is a formula (like =A1 * 10). You don’t manually change the formula’s result; it just “knows” to update whenever the source cell changes.

What is a Computed Signal?

A Computed Signal is a reactive value that is derived from other signals. It is read-only—you cannot use .set() or .update() on it. Its value is always synchronized with the signals it depends on.

The Syntax
You create one by passing a derivation function to the computed() helper:

import { signal, computed } from '@angular/core';

const price = signal(100);
const quantity = signal(2);

// This signal automatically tracks price() and quantity()
const total = computed(() => price() * quantity());
<p>Items: {{ total() }}</p>

Why are they so powerful?

1. Lazy Evaluation
This is the “secret sauce” for performance. A computed signal does not calculate its value until you actually read it.

If price changes 100 times but you never show total on the screen, the multiplication logic never runs.

Once you read it, the result is memoized (cached). If you read it again and the price hasn’t changed, it returns the cached value instantly.

2. Dynamic Dependency Tracking
Computed signals are incredibly smart. They only track signals that were actually used during the last execution.

const showDiscount = signal(false);
const discount = signal(20);

const finalPrice = computed(() => {
  if (showDiscount()) {
    return price() - discount();
  }
  return price();
});

Note: If showDiscount is false, the finalPrice signal will stop listening to the discount signal entirely. It won’t re-calculate even if the discount value changes, saving CPU cycles.

Do’s and Don’ts

Do’s

  • It’s ok to use more than one signal.
computed(() => x() * y() )
  • It’s ok to use writable or computed signals
computed(() => x() * derived() )
  • It’s ok to use constants or immutable non signal data, because signals are not notified if non signal data changes.
computed(() => x() * Math.PI )

Don’ts

  • Don’t use asynchronous code.
// computed is synchronous, async functions will create another task
// DON'T do this
computed( async () => x() * await calc() })
  • Don’t use changeable data that is not a signal.
// DON'T do this
computed(() => x() * Date.now() )
  • Don’t cause side effects, because angular should be able call computed many times without having to worry about side effects.
// DON'T do this
computed(() =>  x() * j++ )
  • Don’t create or modify other signals.
// DON'T do this
computed(() =>  {
  x.update(v => v + 1);
  x() * 10;
})

Thanks for reading. Happy coding!!!

Reference:

Similar Posts