State Management

Angular State Management

As your application grows, passing data between hundreds of components becomes unmanageable.

"State Management" is the architectural practice of centralizing your application's data.

By creating a single source of truth, components can read and update data globally without messy prop drilling.


State with RxJS BehaviorSubject

For small to medium applications, you do not need heavy state libraries.

You can build a perfectly robust state store using an Angular Service and an RxJS BehaviorSubject.

A BehaviorSubject holds the current value and emits it instantly to any new subscribers!

BehaviorSubject Store Example:

import { Injectable } from '@angular/core';
import { BehaviorSubject } from 'rxjs';

@Injectable({ providedIn: 'root' }) export class CartStateService { // Private state, initialized to 0 private cartCount = new BehaviorSubject<number>(0);

// Public observable for components to subscribe to currentCount$ = this.cartCount.asObservable();

updateCart(newCount: number) { // Pushes the new value to all subscribers instantly this.cartCount.next(newCount); } }


Enterprise State with NgRx

For massive enterprise applications, developers use NgRx.

NgRx is a Redux-inspired reactive state management library specifically built for Angular.

It enforces strict rules: state is read-only, and components must dispatch Actions to Reducers to calculate new state.

While highly scalable, NgRx introduces massive amounts of boilerplate code and a steep learning curve.


The Modern Approach: Signals

With Angular 16+, the framework introduced Signals.

Signals provide a vastly simpler, native way to handle reactive state without complex RxJS syntax or NgRx boilerplate.

You simply create a signal in a service, and any component reading that signal automatically updates when it changes!

Signal State Example:

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

@Injectable({ providedIn: 'root' }) export class ThemeStateService { // Global signal for dark mode isDarkMode = signal(false);

toggleTheme() { this.isDarkMode.update(val => !val); } }

This incredibly clean syntax is rapidly becoming the industry standard for Angular state management!


Exercise 1 of 2

?

Which RxJS subject type is best for state management because it always holds and instantly emits the most recent value to new subscribers?

Exercise 2 of 2

?

What is NgRx?