Effect Deep Dive - When & How to Use Effects
Effects in Angular (Signals)
Effects are special functions used with signals.
They are mainly used to react to signal changes inside TypeScript.
Effects help in handling logic when a signal value updates and are important for performance optimization.
What is an Effect
- An effect is defined using
effect(). - It is usually written inside the constructor.
- It always takes a callback function.
- An effect runs automatically when the signal used inside it changes.
- If a signal is not used inside an effect, that signal will not trigger the effect.
Key Rule of Effects
- Only the signal used inside the effect will trigger it.
- If there are multiple signals, the effect reacts only to the ones accessed inside it.
- Effects run once initially, even before any update.
Example Signals Used
speed→ number signalfruit→ string signalcolor→ normal property (not a signal)
What the Effect Does (Speed Example)
- When
speedchanges: 0–80→ color becomes green80–120→ color becomes orange120+→ color becomes red- The updated speed value is logged in the console.
- UI color updates using property binding.
Multiple Effects
- You can use multiple effects in the same component.
- Each effect reacts only to its own signal.
speedeffect does not react tofruitchanges.fruiteffect does not react tospeedchanges.
Code Example
HTML
<h1>Effects</h1>
<h2 [style.color]="color">{{ speed() }}</h2>
<button (click)="increaseSpeed()">Increase Speed</button>
<hr />
<h2>{{ fruit() }}</h2>
<button (click)="changeFruit()">Change fruit</button>
TypeScript
export class App {
speed = signal(0);
fruit = signal('apple');
color = 'black';
constructor() {
effect(() => {
if (this.speed() > 0 && this.speed() < 80) {
this.color = 'green';
}
if (this.speed() >= 80 && this.speed() < 120) {
this.color = 'orange';
}
if (this.speed() >= 120) {
this.color = 'red';
}
console.log('speed :', this.speed());
});
effect(() => {
console.log(this.fruit());
});
}
increaseSpeed() {
this.speed.set(this.speed() + 10);
}
changeFruit() {
this.fruit.set('banana');
}
}
Important Do’s and Don’ts
- Use effects to read signal values.
- Do not update the same signal inside its own effect.
- Avoid calling
set()on a signal inside the effect that depends on it. - Use effects for logging, UI changes, API calls, or side effects.