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
- Local state is used by one component only, such as a menu card that opens and closes:
open = signal(false)in its class is enough. - Shared state is read by many components. Jali's cart is read by Header (the count badge), MenuPage (the Order buttons) and CartPanel (the list). None of them know each other, so the state lives in one service: a store.
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([])
}
}
providedIn: 'root': one instance for the whole app, as in the Services lesson.private items: only the store can write to this signal.this.items.asReadonly()opens a read-only version for components: readable withcartItems(), impossible toset.countandtotalarecomputed: derived fromitems, never stored on their own.add,removeandclearare the only ways to change the cart, and all of them make a new array rather thanpush.
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
- Storing derived values on their own.
countandtotalas separate signals fall behind sooner or later. Derive them withcomputed. - A store signal anyone can write. A public
items = signal(...)lets any componentsetit quietly. Make itprivateand openasReadonly(). pushinto an array inside a signal.computednever hears about it. Useupdate((items) => [...items, item]).- First exercise details.
TodoStoregets@Injectable({ providedIn: 'root' }),private items = signal<string[]>([]),readonly todoItems = this.items.asReadonly(),readonly count = computed(() => this.items().length), andaddItem(item: string)andremoveItem(index: number)that changeitemswith.update(. The grader makes a new store, callsaddItem('a'),addItem('b'),removeItem(0), and expectscount()to be 1. - Second exercise details.
CartStorederivestotalfrom areduceover the prices insidecomputed, andclearCart()writesthis.items.set([]). The grader adds items priced 3 and 4 and expectstotal()to be 7, and afterclearCart()expects 0.
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.