NgRx State Management Angular
In NgRx, Actions, Reducers, and Selectors are the core building blocks of state management. They define how events are dispatched, how state changes occur, and how components can access data efficiently and predictably.
NgRx builds on the Redux pattern and provides utilities such as createAction, createReducer, and createSelector to make state management easier and more type-safe.
*.actions.ts files and represent events like [Counter] Increment or [Auth] Login Success.createReducer and on to map actions to state transitions.createFeatureSelector()) and are reused across components.Actions are simple objects with a type (and optionally a payload). In NgRx we create them using createAction.
// counter.actions.ts - define counter-related events
import { createAction } from '@ngrx/store';
export const increment = createAction('[Counter] Increment');
export const decrement = createAction('[Counter] Decrement');
export const reset = createAction('[Counter] Reset');
Reducers are pure functions: given the previous state and an action, they return the next state without mutating the original one.
// counter.reducer.ts - update state based on actions
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)
);
Selectors encapsulate how to get specific pieces of state. Components subscribe to selectors instead of directly accessing the store shape.
// counter.selectors.ts - expose reusable state readers
import { createSelector, createFeatureSelector } from '@ngrx/store';
export const selectCounterState = createFeatureSelector<number>('count');
export const selectCount = createSelector(
selectCounterState,
(state: number) => state
);
increment() action to the store.state + 1.selectCount selector to read the latest value and updates the view.Because reducers are pure and selectors are reusable, NgRx makes your state management predictable, testable, and easy to reason about.
[Auth] Login Success instead of LOGIN_OK).counter, auth).increment, decrement, and reset actions for a counter app.0.0 on reset.selectCount and use it in a component to display the current count.step value and update your actions, reducer, and selector to support dynamic increments.