0 day streak
javascript / intermediate
Snippet

Managing Side Effects with effect()

The effect() function tracks signal dependencies automatically and re-runs its code whenever any used signal updates.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
export class DashboardComponent {
count = signal(0);
constructor() {
effect(() => {
console.log(`The count changed to: ${this.count()}`);
localStorage.setItem('userCount', this.count().toString());
});
}
}
angular
Breakdown
1
effect(() => { ... })
Registers a reactive side effect that runs within the injection context.
2
this.count()
Reading the signal value automatically adds it as a dependency to the effect.
3
localStorage.setItem
An example of a side effect that synchronizes state with an external API.