Lesson 26 / 30
computed() & effect()
Derive values from signals and run side effects when they change.
computed()
computed() derives a read-only signal from others — it recalculates automatically only when a dependency changes.
import { signal, computed } from '@angular/core';
export class CartComponent {
price = signal(250);
quantity = signal(2);
total = computed(() => this.price() * this.quantity());
}effect()
effect() runs a side effect (logging, localStorage, analytics) automatically whenever the signals it reads change.
import { effect } from '@angular/core';
constructor() {
effect(() => {
console.log('Total is now', this.total());
});
}computed vs effect
Use computed() when you need a value back; use effect() when you just need to do something (no return value) as a reaction.