Signals computed() and effect(): Reactive Logic Done Right
Use computed for derived values and effect for side effects, the safe and modern reactive pattern.
Signals become powerful when you combine: - `computed()` for values derived from other signals - `effect()` for side effects (logging, saving, calling APIs carefully) ## computed(): derived values ```ts import { Component, signal, computed } from '@angular/core'; @Component({ selector: 'app-cart', standalone: true, template: ` <p>Items: {{ items() }}</p> <p>Price each: ${{ price() }}</p> <p>Total: ${{ total() }}</p> `, }) export class CartComponent { items = signal(2); price = signal(25); total = computed(() => this.items() * this.price()); } ``` If items or price changes, total updates automatically. ## effect(): react when signals change ```ts import { effect } from '@angular/core'; constructor() { effect(() => { console.log('Total changed:', this.total()); }); } ``` ### Important rule Use `effect` for side effects, not for computing values. For computed values, use `computed`. ## Practical use case Auto-save a draft when text changes: ```ts draft = signal(''); constructor() { effect(() => { const value = this.draft(); localStorage.setItem('draft', value); }); } ``` > Next: Signals vs Observables, when to choose which one.