Chapter 05

Signals and state

Signals are the biggest change to Angular since Ivy. They replace Zone.js change detection, make OnPush irrelevant, and remove the need for a state-management library in most applications.

⏱ 18 min readLevel: intermediateCore chapter
A writable signal feeding computed signals and effects, forming a dependency graph, next to example code and a comparison with Zone.js
A signal knows who reads it, so a change updates exactly those bindings.

The three primitives

signal, computed, effect
import { signal, computed, effect } from '@angular/core';

// 1 · signal — a writable value
const query = signal('');
query();                       // read
query.set('ORD-10');           // replace
query.update(q => q.trim());   // derive from the current value

// 2 · computed — derived, cached, read-only
const results = computed(() =>
  orders().filter(o => o.reference.includes(query())));

// recalculates ONLY when orders() or query() actually change,
// and only when something reads results()

// 3 · effect — a side effect that reruns when its dependencies change
effect(() => {
  localStorage.setItem('lastQuery', query());
});
signal()computed()effect()
WritableYesNo—
Cached—Yes, until a dependency changes—
Lazy—Yes — never runs if unreadNo, always runs
Returns a valueYesYesNo
Use forSource stateAnything derivableTalking to the outside world
If you can compute it, do not store it

The single most common signal mistake is keeping filteredOrders as its own signal and updating it in three places. It will drift out of sync. Derived state belongs in computed() — one definition, always correct, no synchronisation code.

Effects — use them sparingly

legitimate effect uses
export class OrderListComponent {
  private readonly analytics = inject(AnalyticsService);
  readonly filter = signal<OrderFilter>({ status: null });

  constructor() {
    // persist to storage
    effect(() => localStorage.setItem('filter', JSON.stringify(this.filter())));

    // report to a third party
    effect(() => this.analytics.track('filter_changed', this.filter()));

    // drive an imperative library
    effect(() => this.chart?.setData(this.chartData()));

    // cleanup runs before the next execution and on destroy
    effect(onCleanup => {
      const id = setInterval(() => this.poll(this.filter()), 10_000);
      onCleanup(() => clearInterval(id));
    });
  }
}
An effect that sets another signal is usually a bug

It creates a second source of truth and can loop. Angular will refuse the write outright unless you pass allowSignalWrites, which exists mainly so the error message can point at a real mistake. Reach for computed() or linkedSignal() instead.

linkedSignal — writable, but resettable

the "local edit that resets" pattern (v19+)
export class OrderDetailComponent {
  readonly order = input.required<Order>();

  // starts from the input, but the user may override it;
  // resets automatically whenever a different order arrives
  readonly draftStatus = linkedSignal(() => this.order().status);

  revert(): void {
    this.draftStatus.set(this.order().status);
  }
}

Before linkedSignal this needed an effect plus a guard flag, and it was the classic place for a subtle bug.

A signal store — state management without a library

features/orders/order.store.ts
import { computed, inject, Injectable, signal } from '@angular/core';
import { OrderApi } from './order.api';

interface OrderState {
  orders: Order[];
  loading: boolean;
  error: string | null;
  filter: { status: OrderStatus | null; query: string };
}

@Injectable({ providedIn: 'root' })
export class OrderStore {
  private readonly api = inject(OrderApi);

  // ---- private writable state ----
  private readonly state = signal<OrderState>({
    orders: [],
    loading: false,
    error: null,
    filter: { status: null, query: '' },
  });

  // ---- public read-only selectors ----
  readonly orders  = computed(() => this.state().orders);
  readonly loading = computed(() => this.state().loading);
  readonly error   = computed(() => this.state().error);
  readonly filter  = computed(() => this.state().filter);

  readonly visible = computed(() => {
    const { status, query } = this.filter();
    return this.orders().filter(o =>
      (!status || o.status === status) &&
      (!query  || o.reference.toLowerCase().includes(query.toLowerCase())));
  });

  readonly totalValue = computed(() =>
    this.visible().reduce((sum, o) => sum + o.total, 0));

  readonly isEmpty = computed(() =>
    !this.loading() && this.visible().length === 0);

  // ---- commands ----
  async load(): Promise<void> {
    this.patch({ loading: true, error: null });
    try {
      const orders = await this.api.findAll();
      this.patch({ orders, loading: false });
    } catch (e) {
      this.patch({ loading: false, error: 'Could not load orders' });
    }
  }

  setQuery(query: string): void {
    this.patch({ filter: { ...this.filter(), query } });
  }

  // optimistic update with rollback
  async cancel(id: number): Promise<void> {
    const previous = this.orders();
    this.patch({ orders: previous.map(o =>
      o.id === id ? { ...o, status: 'CANCELLED' as const } : o) });

    try {
      await this.api.cancel(id);
    } catch {
      this.patch({ orders: previous, error: 'Cancel failed' });
    }
  }

  private patch(partial: Partial<OrderState>): void {
    this.state.update(s => ({ ...s, ...partial }));
  }
}

That is roughly 60 lines and it covers what most applications need NgRx for: a single source of truth, derived selectors, async commands, and optimistic updates with rollback.

ApproachReach for it when
Signals inside a componentState belongs to one screen
A signal store serviceTwo or more components share it — the default answer
NgRx SignalStoreYou want entity helpers and conventions, less boilerplate than classic NgRx
Classic NgRx (Redux)You genuinely need time-travel debugging, event sourcing or a very large team needing rigid structure

Interop with RxJS

@angular/core/rxjs-interop
import { toSignal, toObservable } from '@angular/core/rxjs-interop';

// observable → signal (subscription is cleaned up automatically)
readonly user = toSignal(this.auth.user$, { initialValue: null });

// signal → observable, for operators like debounceTime
readonly query = signal('');

readonly results = toSignal(
  toObservable(this.query).pipe(
    debounceTime(300),
    distinctUntilChanged(),
    switchMap(q => this.api.search(q)),
  ),
  { initialValue: [] as Order[] },
);
The rule of thumb

Signals for state — what the UI renders right now. RxJS for events over time — debouncing, cancellation, websockets, retries. Convert at the boundary with toSignal. Chapter 10 covers the operators worth knowing.

Pitfalls

MistakeSymptomFix
Forgetting the call parenthesesTemplate shows function () { … }{{ orders() }}, not {{ orders }}
Mutating the value in placeUI does not updateupdate(v => [...v, item]) — signals compare by reference
Side effect inside computed()Unpredictable executionComputed must be pure; move it to an effect
Storing derived stateValues drift out of synccomputed()
effect() outside an injection contextNG0203 at runtimeCreate it in a field initialiser or pass an injector

Going zoneless

app.config.ts
providers: [
  provideExperimentalZonelessChangeDetection(),   // stable as provideZonelessChangeDetection() in v20
]

Then delete zone.js from angular.json's polyfills. You lose about 35 KB and gain change detection that runs only when a signal actually changes. Requires that all your state is in signals — anything relying on Zone.js to notice a setTimeout mutation will stop updating.

You push into an array held in a signal and the template does not update. Why?

arr().push(x) mutates in place, so the reference is unchanged and the signal sees no change. Use arr.update(list => [...list, x]) to produce a new array — the same immutability rule that applies in React.