How do you use the effect function with signals to run code whenever a signal's value changes?
Short answer
The effect function lets you run a piece of code automatically whenever any signal it reads inside changes, similar to how a computed signal works, but instead of producing a new value, it performs a side effect, such as logging a value or saving data to local storage.
Advertisement
AModel answer
The effect function lets you run a piece of code automatically whenever any signal it reads inside changes, similar to how a computed signal works, but instead of producing a new value, it performs a side effect, such as logging a value or saving data to local storage.
import { signal, effect } from '@angular/core';
count = signal(0);
constructor() {
effect(() => {
console.log('Count changed to', this.count());
});
}Real-world example
A settings component automatically saves a user's theme preference to local storage every time the underlying theme signal changes, using an effect to react to that change without needing a separate manual save button.
Likely follow-ups
- When does an effect actually run for the first time after being created?
- What is the risk of updating a signal from inside an effect that also reads that same signal?
Related topics