AI Hints
Home›Angular Tutorial›computed(), effect() and Signals with Arrays
Angular · Lesson 32 of 120

effect()

Run code when signals change.

⏱ 2 min read▶ Video at 38:55🎓 Free
Watch this lesson in the Angular courseWatch on YouTube ↗Full Angular course

Sometimes, when a signal changes, we want to do something outside the page. Like logging, or saving to the browser's storage. That's an effect.

  • Something outside the page
  • Logging, saving
  • effect

Effects

An effect is a function that reads signals. It runs once at the start, and again whenever those signals change. Create effects in the constructor. And use them rarely, mostly for logging, or saving.

keyvalue
effect(() => ...)runs code
Runsat start, then on changes
Createin the constructor
Use forlogging, saving, rarely

Logging every change

The effect reads quantity, and logs it. It runs once at the start. Then it runs again after every change. We click twice. Run it. The log shows one, then two, then three.

app.tstypescript
import { Component, signal, effect } from '@angular/core';

@Component({
  selector: 'app-root',
  template: `
    <h2>Copies: {{ quantity() }}</h2>
    <button (click)="quantity.update(q => q + 1)">Add a copy</button>
  `,
})
export class App {
  quantity = signal(1);

  constructor() {
    effect(() => {
      console.log(`Quantity is now ${this.quantity()}`);
    });
  }
}
Output
Quantity is now 1
Quantity is now 2
Quantity is now 3
Also uses actions.json
[{"click": "button", "times": 2}]

computed or effect?

Computed makes a new value, from other signals. Effect makes something happen, outside the signals. If you want a value, use computed. Don't use an effect to set other signals.

computed

  • returns a valuepuretotal, isValid, count

effect

  • does somethingside effectslog, save, sync

Summary

Effects run code whenever the signals they read change. Use computed for values, and effect for things like logging. Next, signals that hold arrays.

Key takeaways
  • effect()
  • Runs on change
  • Not for values
Next up: Signals with Arrays — lists that change