← Back to Angular, page 2

angular-0039 · Hard senior

How would you design state management with signals and services, and when would you choose NgRx instead?

A signal store is a service that keeps state in private writable signals, exposes read-only signals and computed values, and changes state only through named methods with immutable updates. It is enough for most apps. NgRx adds actions, reducers, effects, and tooling, which pay off for large teams, complex side-effect flows, and the need to inspect and replay changes.

Full answer

State management means deciding where data lives, who can change it, and how others find out. Start with the smallest tool that works.

Levels:

  1. Local component state: a signal in the component.
  2. Shared feature state: a service with signals, provided at root or at feature route level.
  3. A state library: NgRx (Store, or the lighter NgRx SignalStore), or another library.

A signal store service follows a few rules:

  • State is held in a private WritableSignal. Outside code gets asReadonly() or computed views, so it cannot change state directly.
  • Changes happen through methods named after intent (addItem, clear), which use update with a new object or array, never in-place mutation.
  • Derived values (totals, counts, filtered lists) are computed, not stored copies.
  • Side effects (HTTP, storage) are done in the methods or in an effect, and results flow back as state.
  • Loading and error states are part of the state, so templates can show them.

When to move to NgRx: many teams share one large state, features need strict conventions, you must trace "which action caused this", you need time-travel debugging, undo, or complex orchestration of side effects (cancellation, debouncing, retries), or multiple features react to the same events. The cost is more files and indirection. NgRx SignalStore is a middle path: signals with structure and plugins, with less boilerplate than the classic Store.

Server state (data that lives on the backend) is a separate topic. A cache of fetched data needs invalidation and refetching. Do not copy it into global state without a reason.

Interview tip: say that the choice depends on team size and complexity, and show the simple option first.

typescript
import { Component, Injectable, computed, inject, signal } from '@angular/core';

export interface CartLine {
  id: number;
  name: string;
  price: number;
  qty: number;
}

interface CartState {
  lines: CartLine[];
  status: 'idle' | 'saving' | 'error';
}

@Injectable({ providedIn: 'root' })
export class CartStore {
  private readonly state = signal<CartState>({ lines: [], status: 'idle' });

  readonly lines = computed(() => this.state().lines);
  readonly status = computed(() => this.state().status);
  readonly count = computed(() => this.lines().reduce((sum, l) => sum + l.qty, 0));
  readonly total = computed(() => this.lines().reduce((sum, l) => sum + l.price * l.qty, 0));

  add(item: Omit<CartLine, 'qty'>): void {
    this.state.update((s) => {
      const existing = s.lines.find((l) => l.id === item.id);
      const lines = existing
        ? s.lines.map((l) => (l.id === item.id ? { ...l, qty: l.qty + 1 } : l))
        : [...s.lines, { ...item, qty: 1 }];
      return { ...s, lines };
    });
  }

  remove(id: number): void {
    this.state.update((s) => ({ ...s, lines: s.lines.filter((l) => l.id !== id) }));
  }

  clear(): void {
    this.state.set({ lines: [], status: 'idle' });
  }
}

@Component({
  selector: 'app-canteen-cart',
  template: `
    <button (click)="store.add({ id: 1, name: 'Samosa', price: 15 })">Add samosa</button>
    <button (click)="store.add({ id: 2, name: 'Tea', price: 10 })">Add tea</button>
    <p>{{ store.count() }} items, total {{ store.total() }}</p>
    <ul>
      @for (l of store.lines(); track l.id) {
        <li>{{ l.name }} x {{ l.qty }} <button (click)="store.remove(l.id)">Remove</button></li>
      }
    </ul>
  `,
})
export class CanteenCartComponent {
  protected readonly store = inject(CartStore);
}

Angular 20.3, strict template check passes. Provide the store in a feature route with `providers: [CartStore]` to scope it, or keep `providedIn: 'root'` for app-wide state.

Key points

  • Private writable signal, public read-only views, change through intent-named methods.
  • Immutable updates and `computed` for derived values.
  • Keep loading and error flags in state.
  • NgRx fits large teams, traceability, and complex side-effect orchestration.

Common mistakes

  • Exposing the writable signal, so any component can change state in unplanned ways.
  • Storing derived data (such as a total) as a separate signal that can go out of sync.
  • Using a global store for state that belongs to one component.

Follow-ups

  • What is the difference between NgRx Store and NgRx SignalStore?
  • How would you handle optimistic updates and rollback?
  • Where would you keep server cache data?

Tips

  • Show the small solution first and name the point where you would move to NgRx.
  • Mention immutability, since it also keeps OnPush correct.
  • Say that you treat server data differently from UI state.

Evaluation rubric

  • Designs a clean signal service.
  • Gives concrete criteria for choosing NgRx.
  • Separates server state from client state.