6. NgRx: Store, Actions, Reducers, Selectors & Effects

Predictable state management for Angular applications

As Angular apps grow, the BehaviorSubject-in-a-service pattern starts to strain. Multiple services hold overlapping state. Components reach into several services to assemble their view. State changes trigger cascading updates that are hard to trace. You need a single source of truth with predictable update rules.

NgRx is Angular's implementation of the Redux pattern, built entirely on RxJS. It gives you:

  • A Store — one immutable state tree for your entire application (or feature)
  • Actions — typed events that describe what happened
  • Reducers — pure functions that compute the next state
  • Selectors — composable queries to read state efficiently
  • Effects — RxJS-powered side effects for async work

The Data Flow

Every NgRx interaction follows the same unidirectional cycle:

Component Action Reducer Store Selector dispatch() new state renders Effects new action async

This is strict, verbose, and intentional. You trade brevity for traceability — every state change has a named action, a clear cause, and a predictable result.

Actions: What Happened

Actions are the events of your application. Each action has a type string and optionally carries a payload via props.

import { createAction, props } from '@ngrx/store';

// User actions
export const loadUsers = createAction('[User List] Load Users');

export const loadUsersSuccess = createAction(
  '[User List] Load Users Success',
  props<{ users: User[] }>()
);

export const loadUsersFailure = createAction(
  '[User List] Load Users Failure',
  props<{ error: string }>()
);

export const addUser = createAction(
  '[User Form] Add User',
  props<{ user: Omit<User, 'id'> }>()
);

export const deleteUser = createAction(
  '[User List] Delete User',
  props<{ userId: number }>()
);

Action naming convention

The [Source] Event format tells you where the action was dispatched and what happened:

Part Example Purpose
[Source] [User List] Which component/effect dispatched this
Event Load Users Success What happened (past tense or noun)

This makes the Redux DevTools timeline readable at a glance — you can trace every state change back to its origin.

Actions describe events, not commands

Name actions after what happened, not what you want to happen. loadUsersSuccess (an event) is better than setUsers (a command). This keeps actions decoupled from how they're handled — multiple reducers and effects can respond to the same action.

Reducers: How State Changes

A reducer is a pure function that takes the current state and an action, and returns the next state. It never mutates — it always creates a new state object.

import { createReducer, on } from '@ngrx/store';
import * as UserActions from './user.actions';

export interface UserState {
  users: User[];
  loading: boolean;
  error: string | null;
  selectedUserId: number | null;
}

export const initialState: UserState = {
  users: [],
  loading: false,
  error: null,
  selectedUserId: null
};

export const userReducer = createReducer(
  initialState,

  on(UserActions.loadUsers, (state) => ({
    ...state,
    loading: true,
    error: null
  })),

  on(UserActions.loadUsersSuccess, (state, { users }) => ({
    ...state,
    users,
    loading: false
  })),

  on(UserActions.loadUsersFailure, (state, { error }) => ({
    ...state,
    loading: false,
    error
  })),

  on(UserActions.addUser, (state, { user }) => ({
    ...state,
    // Optimistic update — add with a temp ID
    // The effect will replace it with the server-assigned ID
    users: [...state.users, { ...user, id: Date.now() }]
  })),

  on(UserActions.deleteUser, (state, { userId }) => ({
    ...state,
    users: state.users.filter(u => u.id !== userId),
    selectedUserId: state.selectedUserId === userId ? null : state.selectedUserId
  }))
);

Each on() handler is a mini-function that pattern-matches on an action type. The spread operator (...state) creates a shallow copy, then you override the properties that changed. The old state is never touched.

Registering the reducer

// In your module:
import { StoreModule } from '@ngrx/store';
import { userReducer } from './state/user.reducer';

@NgModule({
  imports: [
    StoreModule.forRoot({ users: userReducer })
    // or for feature modules:
    // StoreModule.forFeature('users', userReducer)
  ]
})
export class AppModule {}

With standalone APIs (Angular 15+):

// In app.config.ts:
import { provideStore } from '@ngrx/store';
import { userReducer } from './state/user.reducer';

export const appConfig: ApplicationConfig = {
  providers: [
    provideStore({ users: userReducer })
  ]
};

Selectors: Reading State

Selectors are pure functions that extract and derive data from the store. They're memoized — if the input state hasn't changed, they return the cached result without recomputing.

import { createFeatureSelector, createSelector } from '@ngrx/store';
import { UserState } from './user.reducer';

// Select the feature slice
export const selectUserState = createFeatureSelector<UserState>('users');

// Select specific properties
export const selectAllUsers = createSelector(
  selectUserState,
  (state) => state.users
);

export const selectUsersLoading = createSelector(
  selectUserState,
  (state) => state.loading
);

export const selectUsersError = createSelector(
  selectUserState,
  (state) => state.error
);

export const selectSelectedUserId = createSelector(
  selectUserState,
  (state) => state.selectedUserId
);

// Derived/computed selectors
export const selectUserCount = createSelector(
  selectAllUsers,
  (users) => users.length
);

export const selectAdminUsers = createSelector(
  selectAllUsers,
  (users) => users.filter(u => u.role === 'admin')
);

export const selectSelectedUser = createSelector(
  selectAllUsers,
  selectSelectedUserId,
  (users, selectedId) => users.find(u => u.id === selectedId) ?? null
);

// Parameterized selector
export const selectUserById = (id: number) => createSelector(
  selectAllUsers,
  (users) => users.find(u => u.id === id) ?? null
);

Composition is the key

Selectors compose like functions. selectAdminUsers builds on selectAllUsers, which builds on selectUserState. If the users array hasn't changed, selectAdminUsers returns its cached result — even if other parts of the state (like loading) changed.

selectUserState selectAllUsers selectAdminUsers selectUserCount selectSelectedUser selectUsersLoading selectUsersError selectSelectedUserId memoized

Why selectors matter for performance

Without selectors, every component subscribing to the store would re-render on any state change, even if the data they care about didn't change. Memoized selectors ensure a component only re-renders when its specific slice of state actually changes. Combined with OnPush change detection, this is extremely efficient.

Using Store in Components

Components dispatch actions and select state. They never directly modify the store.

import { Component } from '@angular/core';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs';
import * as UserActions from '../state/user.actions';
import * as UserSelectors from '../state/user.selectors';

@Component({
  selector: 'app-user-list',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <div class="toolbar">
      <button (click)="loadUsers()">Load Users</button>
      <span>{{ userCount$ | async }} users</span>
    </div>

    <div *ngIf="loading$ | async" class="spinner">Loading...</div>
    <div *ngIf="error$ | async as error" class="error">{{ error }}</div>

    <div class="user-list">
      <div
        *ngFor="let user of users$ | async; trackBy: trackById"
        class="user-card"
        [class.selected]="user.id === (selectedUserId$ | async)"
        (click)="selectUser(user.id)">
        <h3>{{ user.name }}</h3>
        <p>{{ user.email }}</p>
        <span class="role">{{ user.role }}</span>
        <button (click)="deleteUser(user.id); $event.stopPropagation()">
          Delete
        </button>
      </div>
    </div>
  `
})
export class UserListComponent implements OnInit {
  users$ = this.store.select(UserSelectors.selectAllUsers);
  loading$ = this.store.select(UserSelectors.selectUsersLoading);
  error$ = this.store.select(UserSelectors.selectUsersError);
  userCount$ = this.store.select(UserSelectors.selectUserCount);
  selectedUserId$ = this.store.select(UserSelectors.selectSelectedUserId);

  constructor(private store: Store) {}

  ngOnInit() {
    this.loadUsers();
  }

  loadUsers() {
    this.store.dispatch(UserActions.loadUsers());
  }

  selectUser(id: number) {
    this.store.dispatch(UserActions.selectUser({ userId: id }));
  }

  deleteUser(id: number) {
    this.store.dispatch(UserActions.deleteUser({ userId: id }));
  }

  trackById(_: number, user: User) {
    return user.id;
  }
}

The component is purely declarative. It dispatches named actions and reads state through selectors. There's no business logic, no HTTP calls, no state manipulation.

Effects: Side Effects and Async Work

Reducers must be pure — no HTTP calls, no localStorage reads, no timers. That's what Effects are for. An Effect listens for specific actions, performs async work, and dispatches new actions with the results.

import { Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { of } from 'rxjs';
import { map, switchMap, catchError, tap } from 'rxjs/operators';
import * as UserActions from './user.actions';
import { UserApiService } from '../services/user-api.service';

@Injectable()
export class UserEffects {
  constructor(
    private actions$: Actions,
    private userApi: UserApiService
  ) {}

  loadUsers$ = createEffect(() =>
    this.actions$.pipe(
      ofType(UserActions.loadUsers),
      switchMap(() =>
        this.userApi.getAll().pipe(
          map(users => UserActions.loadUsersSuccess({ users })),
          catchError(error =>
            of(UserActions.loadUsersFailure({ error: error.message }))
          )
        )
      )
    )
  );

  addUser$ = createEffect(() =>
    this.actions$.pipe(
      ofType(UserActions.addUser),
      switchMap(({ user }) =>
        this.userApi.create(user).pipe(
          map(createdUser => UserActions.addUserSuccess({ user: createdUser })),
          catchError(error =>
            of(UserActions.addUserFailure({ error: error.message }))
          )
        )
      )
    )
  );

  deleteUser$ = createEffect(() =>
    this.actions$.pipe(
      ofType(UserActions.deleteUser),
      switchMap(({ userId }) =>
        this.userApi.delete(userId).pipe(
          map(() => UserActions.deleteUserSuccess({ userId })),
          catchError(error =>
            of(UserActions.deleteUserFailure({ error: error.message, userId }))
          )
        )
      )
    )
  );
}

How Effects Work

  1. actions$ is an Observable of all dispatched actions in the app
  2. ofType(SomeAction) filters to only the action(s) you care about
  3. switchMap / mergeMap / concatMap performs the async work
  4. The result is a new action, dispatched automatically back to the store
Component dispatches loadUsers Effect catches it ofType() HTTP request fires switchMap() loadUsersSuccess({ users }) Reducer updates state Selector emits users[] Component re-renders async pipe Effect

Effects that don't dispatch

Sometimes you want to perform a side effect (logging, navigation, showing a toast) without dispatching a new action:

logActions$ = createEffect(() =>
  this.actions$.pipe(
    tap(action => console.log('Action:', action.type))
  ),
  { dispatch: false }  // don't dispatch the result
);

navigateOnLogin$ = createEffect(() =>
  this.actions$.pipe(
    ofType(AuthActions.loginSuccess),
    tap(() => this.router.navigate(['/dashboard']))
  ),
  { dispatch: false }
);

showErrorToast$ = createEffect(() =>
  this.actions$.pipe(
    ofType(UserActions.loadUsersFailure, UserActions.deleteUserFailure),
    tap(({ error }) => this.toastService.error(error))
  ),
  { dispatch: false }
);

Choosing the right flattening operator in Effects

Operator Use in Effects when...
switchMap Only the latest matters (loading data, navigation). Cancels in-flight requests
mergeMap Multiple concurrent operations are OK (deleting items, sending analytics)
concatMap Order matters, one at a time (sequential saves, ordered queue)
exhaustMap Ignore new requests while one is in flight (login, form submit)
// Login: ignore clicks while a login is in flight
login$ = createEffect(() =>
  this.actions$.pipe(
    ofType(AuthActions.login),
    exhaustMap(({ credentials }) =>
      this.authApi.login(credentials).pipe(
        map(user => AuthActions.loginSuccess({ user })),
        catchError(error =>
          of(AuthActions.loginFailure({ error: error.message }))
        )
      )
    )
  )
);

Registering Effects

// Module-based:
import { EffectsModule } from '@ngrx/effects';
import { UserEffects } from './state/user.effects';

@NgModule({
  imports: [
    EffectsModule.forRoot([UserEffects])
    // or for feature modules:
    // EffectsModule.forFeature([UserEffects])
  ]
})
export class AppModule {}

// Standalone:
import { provideEffects } from '@ngrx/effects';
import { UserEffects } from './state/user.effects';

export const appConfig: ApplicationConfig = {
  providers: [
    provideStore({ users: userReducer }),
    provideEffects(UserEffects)
  ]
};

A Complete Feature: Todo List

Let's wire up a complete feature to see all the pieces together.

Actions

// todo.actions.ts
import { createAction, props } from '@ngrx/store';

export const loadTodos = createAction('[Todo Page] Load Todos');
export const loadTodosSuccess = createAction(
  '[Todo API] Load Todos Success',
  props<{ todos: Todo[] }>()
);
export const loadTodosFailure = createAction(
  '[Todo API] Load Todos Failure',
  props<{ error: string }>()
);

export const addTodo = createAction(
  '[Todo Page] Add Todo',
  props<{ title: string }>()
);
export const addTodoSuccess = createAction(
  '[Todo API] Add Todo Success',
  props<{ todo: Todo }>()
);

export const toggleTodo = createAction(
  '[Todo Page] Toggle Todo',
  props<{ id: number }>()
);
export const toggleTodoSuccess = createAction(
  '[Todo API] Toggle Todo Success',
  props<{ todo: Todo }>()
);

export const deleteTodo = createAction(
  '[Todo Page] Delete Todo',
  props<{ id: number }>()
);
export const deleteTodoSuccess = createAction(
  '[Todo API] Delete Todo Success',
  props<{ id: number }>()
);

export const setFilter = createAction(
  '[Todo Page] Set Filter',
  props<{ filter: 'all' | 'active' | 'completed' }>()
);

State & Reducer

// todo.reducer.ts
import { createReducer, on } from '@ngrx/store';
import * as TodoActions from './todo.actions';

export interface TodoState {
  todos: Todo[];
  loading: boolean;
  error: string | null;
  filter: 'all' | 'active' | 'completed';
}

const initialState: TodoState = {
  todos: [],
  loading: false,
  error: null,
  filter: 'all'
};

export const todoReducer = createReducer(
  initialState,

  on(TodoActions.loadTodos, state => ({
    ...state, loading: true, error: null
  })),

  on(TodoActions.loadTodosSuccess, (state, { todos }) => ({
    ...state, todos, loading: false
  })),

  on(TodoActions.loadTodosFailure, (state, { error }) => ({
    ...state, loading: false, error
  })),

  on(TodoActions.addTodoSuccess, (state, { todo }) => ({
    ...state, todos: [...state.todos, todo]
  })),

  on(TodoActions.toggleTodoSuccess, (state, { todo }) => ({
    ...state,
    todos: state.todos.map(t => t.id === todo.id ? todo : t)
  })),

  on(TodoActions.deleteTodoSuccess, (state, { id }) => ({
    ...state,
    todos: state.todos.filter(t => t.id !== id)
  })),

  on(TodoActions.setFilter, (state, { filter }) => ({
    ...state, filter
  }))
);

Selectors

// todo.selectors.ts
import { createFeatureSelector, createSelector } from '@ngrx/store';
import { TodoState } from './todo.reducer';

export const selectTodoState = createFeatureSelector<TodoState>('todos');

export const selectAllTodos = createSelector(
  selectTodoState,
  state => state.todos
);

export const selectTodoFilter = createSelector(
  selectTodoState,
  state => state.filter
);

export const selectFilteredTodos = createSelector(
  selectAllTodos,
  selectTodoFilter,
  (todos, filter) => {
    switch (filter) {
      case 'active': return todos.filter(t => !t.completed);
      case 'completed': return todos.filter(t => t.completed);
      default: return todos;
    }
  }
);

export const selectTodoStats = createSelector(
  selectAllTodos,
  (todos) => ({
    total: todos.length,
    active: todos.filter(t => !t.completed).length,
    completed: todos.filter(t => t.completed).length
  })
);

export const selectTodosLoading = createSelector(
  selectTodoState,
  state => state.loading
);

Effects

// todo.effects.ts
import { Injectable } from '@angular/core';
import { Actions, createEffect, ofType } from '@ngrx/effects';
import { of } from 'rxjs';
import { map, switchMap, mergeMap, catchError } from 'rxjs/operators';
import * as TodoActions from './todo.actions';
import { TodoApiService } from '../services/todo-api.service';

@Injectable()
export class TodoEffects {
  constructor(
    private actions$: Actions,
    private todoApi: TodoApiService
  ) {}

  loadTodos$ = createEffect(() =>
    this.actions$.pipe(
      ofType(TodoActions.loadTodos),
      switchMap(() =>
        this.todoApi.getAll().pipe(
          map(todos => TodoActions.loadTodosSuccess({ todos })),
          catchError(error =>
            of(TodoActions.loadTodosFailure({ error: error.message }))
          )
        )
      )
    )
  );

  addTodo$ = createEffect(() =>
    this.actions$.pipe(
      ofType(TodoActions.addTodo),
      concatMap(({ title }) =>
        this.todoApi.create({ title, completed: false }).pipe(
          map(todo => TodoActions.addTodoSuccess({ todo }))
        )
      )
    )
  );

  toggleTodo$ = createEffect(() =>
    this.actions$.pipe(
      ofType(TodoActions.toggleTodo),
      mergeMap(({ id }) =>
        this.todoApi.toggle(id).pipe(
          map(todo => TodoActions.toggleTodoSuccess({ todo }))
        )
      )
    )
  );

  deleteTodo$ = createEffect(() =>
    this.actions$.pipe(
      ofType(TodoActions.deleteTodo),
      mergeMap(({ id }) =>
        this.todoApi.delete(id).pipe(
          map(() => TodoActions.deleteTodoSuccess({ id }))
        )
      )
    )
  );
}

Component

// todo-page.component.ts
@Component({
  selector: 'app-todo-page',
  changeDetection: ChangeDetectionStrategy.OnPush,
  template: `
    <h1>Todos</h1>

    <form (ngSubmit)="addTodo()" class="add-form">
      <input
        [(ngModel)]="newTodoTitle"
        name="title"
        placeholder="What needs to be done?"
        required>
      <button type="submit" [disabled]="!newTodoTitle.trim()">Add</button>
    </form>

    <div class="filters">
      <button
        *ngFor="let f of ['all', 'active', 'completed']"
        (click)="setFilter(f)"
        [class.active]="f === (filter$ | async)">
        {{ f | titlecase }}
      </button>
    </div>

    <div *ngIf="loading$ | async" class="spinner">Loading...</div>

    <ul class="todo-list">
      <li
        *ngFor="let todo of todos$ | async; trackBy: trackById"
        [class.completed]="todo.completed">
        <label>
          <input
            type="checkbox"
            [checked]="todo.completed"
            (change)="toggle(todo.id)">
          {{ todo.title }}
        </label>
        <button (click)="delete(todo.id)" class="delete">x</button>
      </li>
    </ul>

    <ng-container *ngIf="stats$ | async as stats">
      <p class="stats">
        {{ stats.active }} active, {{ stats.completed }} completed,
        {{ stats.total }} total
      </p>
    </ng-container>
  `
})
export class TodoPageComponent implements OnInit {
  private store = inject(Store);

  todos$ = this.store.select(selectFilteredTodos);
  filter$ = this.store.select(selectTodoFilter);
  loading$ = this.store.select(selectTodosLoading);
  stats$ = this.store.select(selectTodoStats);
  newTodoTitle = '';

  ngOnInit() {
    this.store.dispatch(loadTodos());
  }

  addTodo() {
    if (this.newTodoTitle.trim()) {
      this.store.dispatch(addTodo({ title: this.newTodoTitle.trim() }));
      this.newTodoTitle = '';
    }
  }

  toggle(id: number) {
    this.store.dispatch(toggleTodo({ id }));
  }

  delete(id: number) {
    this.store.dispatch(deleteTodo({ id }));
  }

  setFilter(filter: string) {
    this.store.dispatch(setFilter({ filter: filter as 'all' | 'active' | 'completed' }));
  }

  trackById(_: number, todo: Todo) {
    return todo.id;
  }
}

Try It Yourself — NgRx Store Simulator

This is a live simulation of the Todo store from the example above. Dispatch actions and watch the full NgRx cycle: action → reducer → state → selector → render.

Store State
Selectors
Action Log
Rendered Output

DevTools: Why All This Structure Pays Off

Install the Redux DevTools browser extension and add StoreDevtoolsModule to your app:

import { StoreDevtoolsModule } from '@ngrx/store-devtools';

@NgModule({
  imports: [
    StoreDevtoolsModule.instrument({
      maxAge: 50,       // retain last 50 states
      logOnly: false     // restrict to log-only in production
    })
  ]
})
export class AppModule {}

Now you can:

  • Inspect every action and the state before/after
  • Time-travel — replay actions and see the app state at any point
  • Export/import action sequences for bug reproduction
  • Diff states to see exactly what changed

This is why the boilerplate exists. Every action is named and logged. Every state transition is a pure function. You can replay a user's entire session to reproduce a bug.

When to Use NgRx (and When Not To)

NgRx adds significant structure and boilerplate. Use it when:

  • Multiple components need the same data
  • State changes need to be auditable/traceable
  • Complex async workflows with many moving parts
  • Team is large and consistency matters more than speed

Don't use it when:

  • State is local to one component (use component state or signals)
  • A simple service with BehaviorSubject handles the job
  • The app is small and the team is small
  • You're prototyping and need to move fast

The spectrum of state management

ComplexitySolution
Component-localComponent properties, Signals
Shared across a few componentsService with BehaviorSubject
App-wide, complex, needs traceabilityNgRx Store

Start at the top and move down only when you feel the pain of the simpler approach.

File Organization

A typical NgRx feature follows this structure:

src/app/features/users/
  state/
    user.actions.ts       # Action creators
    user.reducer.ts       # Reducer + state interface
    user.selectors.ts     # Selector functions
    user.effects.ts       # Side effects
  services/
    user-api.service.ts   # HTTP calls (no NgRx dependency)
  components/
    user-list/
    user-detail/
    user-form/
  users.module.ts         # Feature module

Keep actions, reducers, selectors, and effects close to the feature they belong to. The API service stays NgRx-agnostic — it just returns Observables. This makes it testable and reusable outside of NgRx.

Series Recap

You've traveled from raw Observables to a full state management architecture:

  1. Observables & Streams — the foundation: lazy, cancelable sequences of values
  2. Operators — map, switchMap, mergeMap, concatMap — transform and control flow
  3. Combining Streams — merge, combineLatest, forkJoin, zip — coordinate multiple sources
  4. Services & DI — encapsulate logic, share state, wire dependencies
  5. Reactive Patterns — Subjects, async pipe, OnPush, fully reactive components
  6. NgRx — Store, Actions, Reducers, Selectors, Effects — predictable state at scale

Each layer builds on the previous one. NgRx Effects are just RxJS pipelines. Selectors return Observables. The async pipe subscribes to them. It's Observables all the way down.