← Back to Angular, page 9

angular-0170 · Medium mid

When does an effect run, how do you stop it tracking a signal with untracked, and how do you clean up with onCleanup?

An effect runs after its first render and again when any signal read inside it changes. Wrap reads you do not want to track in untracked(). Use the onCleanup callback to cancel timers or listeners before the next run and when the effect is destroyed.

Full answer

An effect has two jobs: run code when signals change and keep the outside world (DOM, storage, logging, analytics) in sync. Dependencies are found automatically, only from signals that are actually read during a run.

Timing:

  • A component or directive effect runs during change detection, before the template of that component is checked. It runs once at first, and again after a tracked signal changed. Several changes before the next run give one run.
  • A root effect (created in a service with providedIn: 'root') runs as part of the application's change detection pass, too.
  • Effects need an injection context (constructor or field initialiser), or pass an injector. They stop when the owning component is destroyed.

untracked(() => ...) reads signals without making them dependencies. Example: log the userId whenever page changes, but do not re-run when userId changes. Inside untracked you can also call functions that read other signals, for example a service method, without accidentally subscribing to them.

onCleanup(fn) is the argument of the effect function. The fn runs before the next execution of the effect, and when the effect is destroyed. Use it for clearTimeout, removeEventListener or cancelling a request. Example: when query changes, start a timer for a debounced save, and clear the previous timer in the cleanup.

Writing signals in effects: since Angular 19, signal writes are allowed by default, but they create hidden chains, so keep them for rare cases. If the goal is derived state, use computed or linkedSignal. Use allowSignalWrites only on older versions.

Do not use effects for: copying one signal to another, calling HTTP on every change (use resource or toObservable with switchMap), and triggering navigation as the main data flow.

Test a component effect with fixture.detectChanges() (a root effect with TestBed.tick()), because it does not run at once. Use fake timers for the debounce.

typescript
import { Component, effect, signal, untracked } from '@angular/core';

export const events: string[] = [];

@Component({ selector: 'app-saver', template: `Page {{ page() }}` })
export class SaverComponent {
  readonly page = signal(1);
  readonly userId = signal('u1');
  readonly draft = signal('');

  constructor() {
    // Tracks page only. Reading userId inside untracked does not add a dependency.
    effect(() => {
      const page = this.page();
      const user = untracked(() => this.userId());
      events.push(`visit page ${page} by ${user}`);
    });

    // Debounced save with cleanup: the old timer is cleared before each new run.
    effect((onCleanup) => {
      const text = this.draft();
      if (!text) return;
      const id = setTimeout(() => events.push(`saved "${text}"`), 20);
      onCleanup(() => clearTimeout(id));
    });
  }
}

Angular 20.3, strict template check passes. A Karma test with fake timers (`fakeAsync`) checks that `userId` changes do not re-run the effect, that `page` changes do, and that the previous timer is cleared before the next one.

Key points

  • Effects run during change detection and batch several changes into one run.
  • Only signals read in a run become dependencies. `untracked` removes a read from tracking.
  • `onCleanup` runs before the next run and on destroy. Use it for timers and listeners.
  • Prefer `computed` and `linkedSignal` for derived state.

Common mistakes

  • Reading a signal in an effect and being surprised that it re-runs.
  • Forgetting cleanup, so timers pile up.
  • Using effects as a way to synchronise two signals.

Follow-ups

  • Why does an effect not run at the moment you set a signal?
  • How would you debounce an effect?
  • How do you create an effect outside the constructor?

Tips

  • Show `untracked` with a user id and a page.
  • Show `onCleanup` with a timer.
  • Mention how effects are flushed in tests.

Evaluation rubric

  • Explains effect timing and dependency tracking.
  • Uses `untracked` and `onCleanup` correctly.
  • Knows what effects are not for.