Signal-Native State Management: NgRx SignalStore (@ngrx/signals) vs. ComponentStore
Signal-Native State Management: Organize feature logic using lightweight patterns like NgRx SignalStore (@ngrx/signals) or ComponentStore.
For years, enterprise state management in Angular was dominated by the classic global NgRx Store pattern—actions, reducers, effects, and selectors. While robust for massive distributed architectures, that approach demanded heavy ceremonial overhead: touching four distinct files for a simple property update, juggling multi-stream RxJS pipelines, and handling complex memoized selector trees.
With Angular's reactivity engine standardizing on Signals, modern state management has evolved toward a signal-native paradigm. The leading standard is NgRx SignalStore (@ngrx/signals).
SignalStore delivers a lightweight, fully typed, composable state container built from the ground up for Angular Signals. It bridges the gap between ad-hoc local signal() variables and full-blown global state trees.
## 1. Architectural Comparison
| Dimension | Classic NgRx Global Store | NgRx ComponentStore | Modern NgRx SignalStore (@ngrx/signals) |
| --- | --- | --- | --- |
| Reactivity Primitive | RxJS Observables (select()) | RxJS Observables (select()) | Native Angular Signals |
| Boilerplate | High (Actions, Reducers, Effects, Selectors) | Moderate (Single class with methods) | Minimal (Functional composition via extensions) |
| Authoring Style | Class-based with action dispatchers | Class-based (extends ComponentStore<T>) | Functional & Declarative (signalStore(...)) |
| Tree-Shaking | Coarse across store modules | Good | Optimal (Modular feature extensions) |
| RxJS Dependency | Mandatory across all layers | Mandatory for async flows | Optional (Isolated to rxMethod when streaming) |
| Async Handling | Multi-line createEffect pipelines | this.effect(...) callbacks | Native async/await or rxMethod<T>() |
## 2. Anatomy of NgRx SignalStore
The signalStore() factory composes a store using declarative extension blocks:
```ts
signalStore(
withState(...), // 1. Initial reactive state shape
withComputed(...), // 2. Pure derived signals (auto-memoized)
withMethods(...), // 3. State mutations and async operations
withHooks(...) // 4. Lifecycle hooks (onInit, onDestroy)
)
```
Every property defined inside withState is automatically exposed as a read-only Signal directly on the store instance.
## 3. Step-by-Step Implementation: Building a Feature Store
Here is an enterprise-grade ProjectsStore handling pagination, search filtering, async loading states, and remote HTTP requests.
### 3.1 Defining the Model & State Interfaces
```ts
// src/app/features/projects/models/project.model.ts
export interface Project {
id: string;
name: string;
status: 'active' | 'archived' | 'completed';
budget: number;
}
export interface ProjectsState {
projects: Project[];
isLoading: boolean;
searchFilter: string;
error: string | null;
}
```
### 3.2 The Complete Store Definition (projects.store.ts)
```ts
// src/app/features/projects/state/projects.store.ts
import { inject, computed } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import {
signalStore,
withState,
withComputed,
withMethods,
withHooks,
patchState
} from '@ngrx/signals';
import { rxMethod } from '@ngrx/signals/rxjs-interop';
import { pipe, switchMap, tap, catchError, of, debounceTime, distinctUntilChanged } from 'rxjs';
import { Project, ProjectsState } from '../models/project.model';
const initialState: ProjectsState = {
projects: [],
isLoading: false,
searchFilter: '',
error: null,
};
export const ProjectsStore = signalStore(
// 1. Declare state shape
withState(initialState),
// 2. Derive reactive state via computed signals
withComputed(({ projects, searchFilter }) => ({
filteredProjects: computed(() => {
const term = searchFilter().toLowerCase().trim();
if (!term) return projects();
return projects().filter(p => p.name.toLowerCase().includes(term));
}),
activeProjectsCount: computed(() =>
projects().filter(p => p.status === 'active').length
),
totalBudget: computed(() =>
projects().reduce((acc, p) => acc + p.budget, 0)
)
})),
// 3. Define state mutations and async workflows
withMethods((store, http = inject(HttpClient)) => ({
// Synchronous mutation via patchState
setSearchFilter(searchFilter: string): void {
patchState(store, { searchFilter });
},
// Promise-based async method (No RxJS required for straightforward mutations)
async addProject(newProject: Omit): Promise {
patchState(store, { isLoading: true, error: null });
try {
const created = await fetch('/api/projects', {
method: 'POST',
body: JSON.stringify(newProject),
headers: { 'Content-Type': 'application/json' }
}).then(res => res.json() as Promise);
patchState(store, state => ({
projects: [...state.projects, created],
isLoading: false
}));
} catch (err: unknown) {
patchState(store, {
isLoading: false,
error: 'Failed to create project.'
});
}
},
// RxJS-driven async method via rxMethod (Ideal for debouncing and race conditions)
loadProjectsByQuery: rxMethod(
pipe(
debounceTime(300),
distinctUntilChanged(),
tap(() => patchState(store, { isLoading: true, error: null })),
switchMap(query =>
http.get(`/api/projects?q=${query}`).pipe(
tap(projects => patchState(store, { projects, isLoading: false })),
catchError(err => {
patchState(store, {
error: 'Failed to load projects from server.',
isLoading: false
});
return of([]);
})
)
)
)
)
})),
// 4. Lifecycle hooks
withHooks({
onInit(store) {
store.loadProjectsByQuery('');
},
onDestroy() {
console.log('ProjectsStore destroyed.');
}
})
);
```
## 4. How patchState() Guarantees Immutability
SignalStore replaces rigid reducer switch blocks with patchState(). It takes either a partial state object or an updater callback:
```ts
// 1. Partial object update (shallow merge)
patchState(store, { isLoading: true });
// 2. Updater function (safely reads prior state)
patchState(store, (state) => ({
projects: state.projects.filter(p => p.id !== targetId),
isLoading: false
}));
// 3. Batching multiple updates in a single tick
patchState(
store,
{ isLoading: true },
(state) => ({ searchFilter: state.searchFilter.trim() })
);
```
## 5. Consuming the Store in Components
Because ProjectsStore integrates with Angular's dependency injection system, you can scope it at any level of your application hierarchy.
### 5.1 Component-Level Scope (Isolated Local State)
Declaring the store in a component's providers array ties its lifecycle directly to that view:
```ts
// src/app/features/projects/projects-view.component.ts
import { Component, inject } from '@angular/core';
import { CurrencyPipe } from '@angular/common';
import { ProjectsStore } from './state/projects.store';
@Component({
selector: 'app-projects-view',
standalone: true,
imports: [CurrencyPipe],
providers: [ProjectsStore], // Scoped strictly to this component subtree
template: `
@if (store.isLoading()) {
{
constructor() {
super({ todos: [] });
}
// Requires pipe-and-select streams
readonly todos$ = this.select(state => state.todos);
// Mutations run through updater closures
readonly addTodo = this.updater((state, todo: Todo) => ({
todos: [...state.todos, todo]
}));
}
```
### Migration Guidance
- **Use SignalStore for modern Angular applications:** It aligns natively with Angular's reactive core, removes template async pipe unwrapping, prevents memory leaks from unclosed subscriptions, and enables functional composition.
Keep ComponentStore only when maintaining existing systems: If an established codebase is deeply coupled to complex RxJS operator pipelines and has not begun adopting Signals, migrating immediately may yield lower ROI than modernizing greenfield features first.
Project Dashboard
Active: {{ store.activeProjectsCount() }}
Total Budget: {{ store.totalBudget() | currency }}
Fetching projects...
}
@if (store.error(); as errorMessage) {
}
@for (item of store.filteredProjects(); track item.id) {
} @empty {
@if (!store.isLoading()) {
`
})
export class ProjectsViewComponent {
// Read state properties directly via signal invocations: store.propertyName()
readonly store = inject(ProjectsStore);
}
```
### 5.2 Root-Level Scope (Global State Singleton)
For shared session state, user settings, or global caching across routes, configure \{ providedIn: 'root' \}:
```ts
export const GlobalUserStore = signalStore(
{ providedIn: 'root' },
withState({ currentUser: null, isAuthenticated: false })
// ...
);
```
## 6. Scalable Composition: Reusable Custom Extensions
When multiple feature stores share repetitive patterns—such as pagination, tracking status flags, or audit logging—extract them into reusable modular slices with signalStoreFeature():
### 6.1 Creating a Reusable Request Status Feature
```ts
// src/app/shared/state/request-status.feature.ts
import { computed } from '@angular/core';
import { signalStoreFeature, withState, withComputed } from '@ngrx/signals';
export type RequestStatus = 'idle' | 'pending' | 'fulfilled' | { error: string };
export function withRequestStatus() {
return signalStoreFeature(
withState({ requestStatus: 'idle' as RequestStatus }),
withComputed(({ requestStatus }) => ({
isPending: computed(() => requestStatus() === 'pending'),
isFulfilled: computed(() => requestStatus() === 'fulfilled'),
errorMessage: computed(() => {
const status = requestStatus();
return typeof status === 'object' ? status.error : null;
})
}))
);
}
```
### 6.2 Composing the Feature into Any Store
Plug withRequestStatus() directly into your store pipeline:
```ts
import { signalStore, withMethods, patchState } from '@ngrx/signals';
import { withRequestStatus } from './request-status.feature';
export const CustomerStore = signalStore(
withState({ customers: [] }),
withRequestStatus(), // Injects requestStatus, isPending, isFulfilled, errorMessage
withMethods((store) => ({
async loadCustomers() {
patchState(store, { requestStatus: 'pending' });
try {
const data = await fetch('/api/customers').then(r => r.json());
patchState(store, { customers: data, requestStatus: 'fulfilled' });
} catch (e: any) {
patchState(store, { requestStatus: { error: e.message } });
}
}
}))
);
```
## 7. What About ComponentStore?
@ngrx/componentstore served as the bridge between global stores and localized state, but it remains fundamentally coupled to RxJS:
```ts
// Legacy ComponentStore pattern (Observable-centric)
export class TodoStore extends ComponentStore{{ item.name }}
Status: {{ item.status }} {{ item.budget | currency }}No matching projects found.
} }