Angular › Angular Signals
How do you use the effect function with signals to run code whenever a signal's value changes?
IntermediateAnswer
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.