effect()
Runs a side effect whenever any signal it reads changes.
Syntax
effect(effectFn: (onCleanup) => void, options?): EffectRef Parameters
| Name | Type | Required | Description |
|---|---|---|---|
effectFn | (onCleanup: (fn: () => void) => void) => void | No | Function executed reactively; register teardown via onCleanup. |
options | object | No | Optional config such as injector or manualCleanup. |
Returns
EffectRef — Handle with a destroy() method to stop the effect.
Examples
import { Component, signal, effect } from '@angular/core';
@Component({ selector: 'app-logger', standalone: true, template: '' })
export class LoggerComponent {
count = signal(0);
constructor() {
effect(() => console.log('count is', this.count()));
}
}
effect((onCleanup) => {
const id = setInterval(() => console.log('tick'), 1000);
onCleanup(() => clearInterval(id));
});
Notes
Effects run at least once and then re-run whenever a tracked signal changes.
Create them in an injection context (constructor or field initializer) so
they are cleaned up with the component. Do not set signals inside an effect
unless you opt in with allowSignalWrites; prefer computed for derived state.