State Management in Angular

Shared state, like the cart that Header, MenuPage and CartPanel read, lives in one providedIn: 'root' service: a signal store. Keep the data in private items…

The header says your cart holds 2 items, but the list below it shows only one. Bugs like this appear when the same number is stored in two places and only one gets updated.

State is the data an app is holding right now: what's in the cart, who's logged in, which menu filter is picked. State management is deciding where that data lives and who may change it, so every part of the page shows the same numbers. Picture the order board on the wall of Jali's stall. The cashier, the kitchen and the courier all read the same board, and only Jali writes on it. The total on the receipt is worked out from the board, not noted down separately. If the courier kept his own tally in a pocket notebook, sooner or later it would differ from the board.

Local state and shared state

Signal store: a service that guards the state

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

export interface Item {
  name: string
  price: number
}

@Injectable({ providedIn: 'root' })
export class CartStore {
  private items = signal<Item[]>([])

  readonly cartItems = this.items.asReadonly()
  readonly count = computed(() => this.items().length)
  readonly total = computed(() => {
    console.log('total recomputed')
    return this.items().reduce((t, item) => t + item.price, 0)
  })

  add(item: Item) {
    this.items.update((items) => [...items, item])
  }

  remove(index: number) {
    this.items.update((items) => items.filter((_, i) => i !== index))
  }

  clear() {
    this.items.set([])
  }
}

Used in components

@Component({
  selector: 'app-header',
  standalone: true,
  template: `<p class="badge">Items: {{ store.count() }}, {{ '$' + store.total() }}</p>`,
})
export class Header {
  store = inject(CartStore)
}

// MenuPage template:       <button (click)="store.add(m)">Order</button>
// CartPanel template: <button (click)="store.remove($index)">Remove</button>
Event cartItems() Header Console
The app opens [] Items: 0, $0 total recomputed
Order Chocolate Cheese Pancake (8) 1 item Items: 1, $8 total recomputed
Order Special Egg Pancake (10) 2 items Items: 2, $18 total recomputed
Throw out the first item 1 item Items: 1, $10 total recomputed

MenuPage never tells Header anything. Only items in the store changes, and computed works total out again once each time items changes, then hands the result to everyone who reads it.

One source of truth

Compare a store that keeps its derived values on their own:

readonly count = signal(0)
readonly total = signal(0)

add(item: Item) {
  this.items.update((items) => [...items, item])
  this.count.update((n) => n + 1)
  this.total.update((t) => t + item.price)
}

remove(index: number) {
  this.items.update((items) => items.filter((_, i) => i !== index))
  // forgot to update count and total
}
Event cartItems() Header
Order 2 pancakes 2 items Items: 2, $18
Throw 1 out 1 item Items: 2, $18

Header still says 2 items though the cart holds one. There are two sources of truth, items and count, and every method must remember to update both. The moment one forgets, the numbers differ. With computed there's nothing to remember: the count and the total are always worked out from items.

asReadonly: only the store may change it

If CartPanel writes this.store.cartItems.set([]), a CLI project fails to compile:

Property 'set' does not exist on type 'Signal<Item[]>'.

Components can only ask for changes through the store's methods, such as this.store.clear(). So if the cart suddenly empties, you only have to look for who calls clear().

When NgRx

Signals are built into Angular (since version 16, stable since 17), and a service with signals like CartStore is enough for most apps. NgRx is a popular state management library for Angular inspired by Redux: all state lives in one Store, changes only through actions handled by reducers, and is read through selectors.

// NgRx style (a separate library, not in the Playground)
export const add = createAction('[Menu] Add', props<{ item: Item }>())

export const cartReducer = createReducer(
  { items: [] as Item[] },
  on(add, (state, { item }) => ({ ...state, items: [...state.items, item] })),
)

// in a component: this.store.dispatch(add({ item: m }))
Need Choice
used by one component a signal in that component
shared by a few components a signal store like CartStore
a tricky async flow (debounce, cancelling old requests) service + RxJS
one shared pattern for many stores in a team, still with signals and no actions NgRx SignalStore (@ngrx/signals)
complex state shared by many components, a big team, a trail of every change in DevTools NgRx

Start with signals. Move up to NgRx when the benefit is clear, because every change then needs its own action, reducer and selector.

In between: NgRx SignalStore. NgRx also has the @ngrx/signals package. It still holds signals, with no actions or reducers, but every store is written in the same pattern. The CartStore above, as a SignalStore:

import { computed } from '@angular/core'
import { patchState, signalStore, withComputed, withMethods, withState } from '@ngrx/signals'

export const CartStore = signalStore(
  { providedIn: 'root' },
  withState({ items: [] as Item[] }),
  withComputed(({ items }) => ({ total: computed(() => items().reduce((t, i) => t + i.price, 0)) })),
  withMethods((store) => ({ add: (item: Item) => patchState(store, { items: [...store.items(), item] }) })),
)

A component uses it like a service: store = inject(CartStore), then store.add(m) and {{ store.total() }}. Tried with @ngrx/signals 22.0.1: after two items priced 10 and 7, store.total() holds 17.

⚠️ Numbers that fall behind, and a store anyone can write to

TL;DR: Shared state, like the cart that Header, MenuPage and CartPanel read, lives in one providedIn: 'root' service: a signal store. Keep the data in private items = signal(...), open asReadonly() for reading, derive count and total with computed so there's one source of truth, and change it through methods that make a new array. A derived value stored separately is bound to fall behind. Signals are Angular's built-in feature and enough for most state; NgRx, a Redux-style library, is for complex state shared by many components in a big app.

⚡ Signal store: one service guards the state

Write:

@Injectable({ providedIn: 'root' })
export class CartStore {
  private items = signal<Item[]>([])
  readonly cartItems = this.items.asReadonly()

  add(item: Item) {
    this.items.update((items) => [...items, item])
  }
}

Meaning: Only the store can write to items. Components read through cartItems(), a read-only version that can't be set, and change it only through methods that make a new array.

In the exercise, the grader makes a new store, calls addItem('a'), addItem('b'), removeItem(0), then expects count() to be 1.

⚡ Derive it, don't store it twice

Write:

readonly count = computed(() => this.items().length)
readonly total = computed(() => this.items().reduce((t, item) => t + item.price, 0))
Guess first: count is kept as a signal of its own, and remove() forgets to update it. Order 2 pancakes, remove 1. What does the header say?

Still 2 items, though the cart holds one. There are now two sources of truth, items and count, and the moment one method forgets, the numbers differ.

Meaning: With computed there's nothing to remember: the count and the total are always worked out from items.

⚡ When NgRx

Meaning: Signals are built into Angular and enough for most state. NgRx, a Redux-style library, is for complex state shared by many components in a big app. Every change then needs its own action, reducer and selector, so start with signals.

What you will learn