BACK
Use casesLocal reducer store — scan as a mini-store
Use cases · 41

Local reducer store — scan as a mini-store

Pattern

A component has a TODO list, checkboxes, a multi-step wizard — it needs add/toggle/remove logic. Pulling in NgRx for that is overkill. Build a mini-store on Subject + scan: actions in → state out.

The problem it solves

Imperative add/toggle/remove methods mutate component fields, and complex sequences easily produce unpredictable bugs. Testing "this chain of actions leads to this state" is very awkward.

Operators and why they matter

  • Subject — receives actions ({type: 'add', id: 'milk'}).
  • scan — a pure reducer of action and previous state. That's the store.
  • map — a derived summary for the UI (count, filtered items).
  • shareReplay({ bufferSize: 1, refCount: true }) — caches the last state for several subscribers.

Gotchas

  • The reducer MUST be a pure function. Mutating state in-place breaks OnPush change detection and distinctUntilChanged.
  • BehaviorSubject with manual next is simpler to start with, but a scan-store tests better with marbles and captures the action history explicitly.
  • For shared cross-route state (a cart, a profile) a local store is too narrow — the state dies with the component.

What you get

State transitions become sequential and testable. The NgRx approach without NgRx.

script.ts // TypeScript
CONSOLE · Console output
Hit Run to see the result...