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.
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!
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);
}
}
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.
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!
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!
Which RxJS subject type is best for state management because it always holds and instantly emits the most recent value to new subscribers?
What is NgRx?