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

  1. An effect is defined using effect().
  2. It is usually written inside the constructor.
  3. It always takes a callback function.
  4. An effect runs automatically when the signal used inside it changes.
  5. If a signal is not used inside an effect, that signal will not trigger the effect.


Key Rule of Effects

  1. Only the signal used inside the effect will trigger it.
  2. If there are multiple signals, the effect reacts only to the ones accessed inside it.
  3. Effects run once initially, even before any update.


Example Signals Used

  1. speed → number signal
  2. fruit → string signal
  3. color → normal property (not a signal)


What the Effect Does (Speed Example)

  1. When speed changes:
  2. 0–80 → color becomes green
  3. 80–120 → color becomes orange
  4. 120+ → color becomes red
  5. The updated speed value is logged in the console.
  6. UI color updates using property binding.


Multiple Effects

  1. You can use multiple effects in the same component.
  2. Each effect reacts only to its own signal.
  3. speed effect does not react to fruit changes.
  4. fruit effect does not react to speed changes.


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

  1. Use effects to read signal values.
  2. Do not update the same signal inside its own effect.
  3. Avoid calling set() on a signal inside the effect that depends on it.
  4. Use effects for logging, UI changes, API calls, or side effects.