An effect is triggered, whenever the Signals it captures is changing. It can be used to react to changes in state. Similar to useEffect in React.js.
However, the Angular docs state that developers should always try to reach for linkedSignal and computed first.
For more on computed see here: Signals
Syntax
theme = signal<'light' | 'dark'>('light');
effect(() => {
localStorage.setItem('theme', this.theme());
console.log('Theme saved to localStorage:', this.theme());
});
When to use and when not
Use cases:
- Logging
- Syncing state to local storage, cookies etc.
- Custom DOM elements and canvas