Angular State Management NgRx Store
NgRx is a powerful state management library for Angular applications, inspired by Redux. It provides a predictable state container using Actions, Reducers, and Selectors, making medium-to-large Angular applications more scalable, testable, and maintainable.
Instead of each component managing its own state independently, NgRx centralizes it in a single Store, so the entire app state becomes easier to reason about and debug.
[Auth] User Logged In).In NgRx, you typically define:
createAction.createReducer and on to respond to actions.createSelector or simple functions to read state.StoreModule.forRoot() or forFeature().The typical data flow is: Component dispatches Action → Reducer updates Store → Selectors read updated state.
A minimal example showing actions, reducer, and store registration.
// actions/counter.actions.ts - defines the counter-related actions
import { createAction } from '@ngrx/store';
export const increment = createAction('[Counter] Increment');
export const decrement = createAction('[Counter] Decrement');
export const reset = createAction('[Counter] Reset');
// reducers/counter.reducer.ts - pure function describing how state changes
import { createReducer, on } from '@ngrx/store';
import { increment, decrement, reset } from './counter.actions';
export const initialState = 0;
export const counterReducer = createReducer(
initialState,
on(increment, state => state + 1),
on(decrement, state => state - 1),
on(reset, _ => 0)
);
// app.module.ts - register the reducer in the root store
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { StoreModule } from '@ngrx/store';
import { AppComponent } from './app.component';
import { counterReducer } from './reducers/counter.reducer';
@NgModule({
declarations: [AppComponent],
imports: [
BrowserModule,
StoreModule.forRoot({ count: counterReducer })
],
bootstrap: [AppComponent]
})
export class AppModule { }
increment() describe what happened (for example, user clicked a button).state + 1).StoreModule.forRoot({ count: counterReducer })) holds the current value of count for the whole app.store.dispatch(increment()) and store.select('count').Sample timeline:
count = 0increment() → state becomes 1increment() again → state becomes 2reset() → state becomes 0createReducer and createAction to reduce boilerplate.