State management means deciding where data lives, who can change it and how components learn about changes. In Angular, choose the simplest option that fits the app. 1. Component state Local UI state (an open menu, form input) stays in the component, ideally as signals: isOpen = signal(false); 2. Services with signals or RxJS — most applications A singleton service holds shared state and exposes read-only views: @Injectable({ providedIn: 'root' }) export class CartStore { private readonly items = signal<CartItem[]>([]); readonly cartItems = this.items.asReadonly(); readonly total = computed(() => this.items().reduce((s, i) => s + i.price * i.qty, 0)); add(item: CartItem) { this.items.update(list => [...list, item]); } } Before signals, the same pattern used a private BehaviorSubject with a public asObservable(). Keep updates immutable and inside the service, so changes are predictable. 3. NgRx Store (Redux pattern) — large, complex apps - Actions describe events, reducers produce new state immutably, selectors read state, and effects handle side effects such as API calls. - Benefits: predictable data flow, Redux DevTools time-travel debugging, clear structure for big teams. - Cost: more boilerplate. NgRx also offers lighter options: @ngrx/signals SignalStore and ComponentStore for feature-level state. 4. Server state Data from APIs (lists, details) has caching and refetching concerns. Keep it in services with caching, or use a library such as TanStack Query for Angular, rather than copying everything into a global store. 5. URL state Filters, pagination and selected tabs often belong in route and query parameters so they survive refresh and can be shared. How to choose: - Small or medium app: signals in services. - Many teams, complex workflows, a need for strong traceability: NgRx Store or SignalStore. - Always: keep state minimal, derive the rest with computed values, and avoid duplicating the same data in several places.
Ravindra Wadile · · 0 likes