0
# NgRx Store
1
2
NgRx Store is a comprehensive state management library for Angular applications that implements the Redux pattern using RxJS. It provides a centralized, immutable state container with reactive state management, type-safe actions, memoized selectors, and comprehensive development tools integration.
3
4
## Package Information
5
6
- **Package Name**: @ngrx/store
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @ngrx/store`
10
- **Peer Dependencies**: `@angular/core ^20.0.0`, `rxjs ^6.5.3 || ^7.5.0`
11
12
## Core Imports
13
14
```typescript
15
import { Store, createAction, createReducer, createSelector, on } from "@ngrx/store";
16
```
17
18
For testing:
19
20
```typescript
21
import { provideMockStore, MockStore } from "@ngrx/store/testing";
22
```
23
24
## Basic Usage
25
26
```typescript
27
import { Component, inject } from "@angular/core";
28
import { Store, createAction, createReducer, createSelector, on, props } from "@ngrx/store";
29
30
// Define actions
31
export const increment = createAction('[Counter] Increment');
32
export const decrement = createAction('[Counter] Decrement');
33
export const reset = createAction('[Counter] Reset');
34
export const setValue = createAction(
35
'[Counter] Set Value',
36
props<{ value: number }>()
37
);
38
39
// Define state
40
interface CounterState {
41
count: number;
42
}
43
44
const initialState: CounterState = { count: 0 };
45
46
// Create reducer
47
const counterReducer = createReducer(
48
initialState,
49
on(increment, (state) => ({ ...state, count: state.count + 1 })),
50
on(decrement, (state) => ({ ...state, count: state.count - 1 })),
51
on(reset, () => initialState),
52
on(setValue, (state, { value }) => ({ ...state, count: value }))
53
);
54
55
// Create selector
56
const selectCount = createSelector(
57
(state: { counter: CounterState }) => state.counter,
58
(counter) => counter.count
59
);
60
61
// Use in component
62
@Component({
63
selector: 'app-counter',
64
template: `
65
<div>Count: {{ count() }}</div>
66
<button (click)="increment()">+</button>
67
<button (click)="decrement()">-</button>
68
<button (click)="reset()">Reset</button>
69
`
70
})
71
export class CounterComponent {
72
private store = inject(Store);
73
74
count = this.store.selectSignal(selectCount);
75
76
increment() { this.store.dispatch(increment()); }
77
decrement() { this.store.dispatch(decrement()); }
78
reset() { this.store.dispatch(reset()); }
79
}
80
```
81
82
## Architecture
83
84
NgRx Store is built around several key architectural patterns:
85
86
- **Redux Pattern**: Unidirectional data flow with actions, reducers, and centralized state
87
- **Reactive Programming**: RxJS integration for reactive state management and side effects
88
- **Type Safety**: Comprehensive TypeScript support with action creators and typed selectors
89
- **Immutability**: Enforced immutable state updates with runtime checks
90
- **Angular Integration**: Deep integration with Angular's dependency injection and lifecycle
91
- **Signal Support**: Modern Angular Signals integration for reactive UI updates
92
- **Lazy Loading**: Feature-based state organization with dynamic reducer loading
93
94
## Capabilities
95
96
### Store Service
97
98
Core reactive state container that provides dispatch and selection capabilities. Extends Observable for reactive state access with Angular Signals support.
99
100
```typescript { .api }
101
class Store<T = object> extends Observable<T> implements Observer<Action> {
102
selectSignal<K>(selector: (state: T) => K, options?: SelectSignalOptions<K>): Signal<K>;
103
dispatch<V extends Action>(action: V): void;
104
dispatch<V extends () => Action>(dispatchFn: V, config?: { injector: Injector }): EffectRef;
105
select<K>(mapFn: (state: T) => K): Observable<K>;
106
addReducer<State, Actions extends Action>(key: string, reducer: ActionReducer<State, Actions>): void;
107
removeReducer<Key extends Extract<keyof T, string>>(key: Key): void;
108
}
109
```
110
111
[Store Service](./store-service.md)
112
113
### Action Creators
114
115
Type-safe action creation with payload validation and action group organization. Supports both individual actions and grouped actions with shared sources.
116
117
```typescript { .api }
118
function createAction<T extends string>(type: T): ActionCreator<T, () => Action<T>>;
119
function createAction<T extends string, P extends object>(
120
type: T,
121
config: ActionCreatorProps<P>
122
): ActionCreator<T, (props: P) => P & Action<T>>;
123
124
function createActionGroup<Source extends string, Events>(
125
config: ActionGroupConfig<Source, Events>
126
): ActionGroup<Source, Events>;
127
128
function props<P>(): ActionCreatorProps<P>;
129
```
130
131
[Action Creators](./action-creators.md)
132
133
### Reducer Creators
134
135
Simplified reducer creation with type-safe action handling using the `on` function pattern. Supports initial state and multiple action handlers.
136
137
```typescript { .api }
138
function createReducer<State>(
139
initialState: State,
140
...ons: ReducerTypes<State, any>[]
141
): ActionReducer<State>;
142
143
function on<State, Creators extends readonly ActionCreator[]>(
144
...args: [...creators: Creators, reducer: OnReducer<State, Creators>]
145
): ReducerTypes<State, Creators>;
146
```
147
148
[Reducer Creators](./reducer-creators.md)
149
150
### Selectors
151
152
Memoized state selection with composition and performance optimization. Supports feature selectors, composed selectors, and custom memoization strategies.
153
154
```typescript { .api }
155
function createSelector<Selectors extends readonly any[], Result>(
156
selectors: [...Selectors],
157
projector: (...args: SelectorResults<Selectors>) => Result
158
): MemoizedSelector<any, Result>;
159
160
function createFeatureSelector<T, K extends keyof T>(
161
featureKey: K
162
): MemoizedSelector<T, T[K]>;
163
164
function createSelectorFactory<T, V>(
165
memoize: MemoizeFn
166
): SelectorFactory<T, V>;
167
```
168
169
[Selectors](./selectors.md)
170
171
### Feature Management
172
173
Modular state organization with lazy-loaded features and automatic selector generation. Supports feature state isolation and dynamic loading.
174
175
```typescript { .api }
176
function createFeature<FeatureName extends string, FeatureState>(
177
config: FeatureConfig<FeatureName, FeatureState>
178
): Feature<FeatureName, FeatureState>;
179
180
interface FeatureConfig<FeatureName extends string, FeatureState> {
181
name: FeatureName;
182
reducer: ActionReducer<FeatureState>;
183
}
184
```
185
186
[Feature Management](./feature-management.md)
187
188
### Module Configuration
189
190
NgModule-based configuration for traditional Angular applications with root and feature module support.
191
192
```typescript { .api }
193
class StoreModule {
194
static forRoot<T, V extends Action = Action>(
195
reducers?: ActionReducerMap<T, V>,
196
config?: RootStoreConfig<T, V>
197
): ModuleWithProviders<StoreRootModule>;
198
199
static forFeature<T, V extends Action = Action>(
200
featureName: string,
201
reducers: ActionReducerMap<T, V> | ActionReducer<T, V>,
202
config?: StoreConfig<T, V>
203
): ModuleWithProviders<StoreFeatureModule>;
204
}
205
```
206
207
[Module Configuration](./module-configuration.md)
208
209
### Standalone Providers
210
211
Modern standalone application support with environment providers for root and feature state configuration.
212
213
```typescript { .api }
214
function provideStore<T, V extends Action = Action>(
215
reducers?: ActionReducerMap<T, V>,
216
config?: RootStoreConfig<T, V>
217
): EnvironmentProviders;
218
219
function provideState<T, V extends Action = Action>(
220
featureName: string,
221
reducers: ActionReducerMap<T, V> | ActionReducer<T, V>,
222
config?: StoreConfig<T, V>
223
): EnvironmentProviders;
224
```
225
226
[Standalone Providers](./standalone-providers.md)
227
228
### Testing Utilities
229
230
Comprehensive testing support with mock store implementations and selector overrides for unit testing.
231
232
```typescript { .api }
233
function provideMockStore<T>(config?: MockStoreConfig<T>): Provider[];
234
function createMockStore<T>(config?: MockStoreConfig<T>): MockStore<T>;
235
236
class MockStore<T> extends Store<T> {
237
overrideSelector<Result>(selector: MemoizedSelector<any, Result>, value: Result): void;
238
refreshState(): void;
239
setState(nextState: T): void;
240
}
241
```
242
243
[Testing Utilities](./testing-utilities.md)
244
245
## Types and Constants
246
247
### Core Types
248
249
Essential type definitions for NgRx Store integration and extension.
250
251
```typescript { .api }
252
/**
253
* Base action type with required type property
254
*/
255
interface Action<Type extends string = string> {
256
type: Type;
257
}
258
259
/**
260
* Infers action type from action creator
261
*/
262
type ActionType<A> = A extends ActionCreator<infer T, infer C>
263
? ReturnType<C> & { type: T }
264
: never;
265
266
/**
267
* Store feature configuration interface
268
*/
269
interface StoreFeature<T, V extends Action = Action> {
270
key: string;
271
reducers: ActionReducerMap<T, V> | ActionReducer<T, V>;
272
reducerFactory: ActionReducerFactory<T, V>;
273
initialState?: InitialState<T>;
274
metaReducers?: MetaReducer<T, V>[];
275
}
276
277
/**
278
* Initial state type - can be partial state, factory function, or void
279
*/
280
type InitialState<T> = Partial<T> | TypeId<Partial<T>> | void;
281
282
/**
283
* Factory function type for initial state
284
*/
285
type TypeId<T> = () => T;
286
```
287
288
### Utility Types
289
290
Type utilities for compile-time validation and type safety.
291
292
```typescript { .api }
293
/**
294
* Compile-time check to prevent dispatching action creators directly
295
*/
296
type CreatorsNotAllowedCheck<T> = T extends ActionCreator
297
? 'Action creator is not allowed to be dispatched. Did you forget to call it?'
298
: unknown;
299
300
/**
301
* Type-level validation for disallowed properties in action payloads
302
*/
303
type NotAllowedCheck<T> = T extends any[]
304
? 'action creator cannot return an array'
305
: T extends { type: any }
306
? 'action creator cannot return an object with a property named `type`'
307
: T extends Record<string, never>
308
? 'action creator cannot return an empty object'
309
: unknown;
310
311
/**
312
* Flattens intersection types for better IntelliSense
313
*/
314
type Prettify<T> = {
315
[K in keyof T]: T[K];
316
} & {};
317
```
318
319
### Constants
320
321
Core action constants used by NgRx Store internally.
322
323
```typescript { .api }
324
/**
325
* Initial action dispatched when store is created
326
*/
327
const INIT: '@ngrx/store/init';
328
329
/**
330
* Action dispatched when reducers are updated dynamically
331
*/
332
const UPDATE: '@ngrx/store/update-reducers';
333
```
334
335
### Mock Environment Functions
336
337
Utilities for configuring NgRx in testing environments.
338
339
```typescript { .api }
340
/**
341
* Sets NgRx mock environment flag for testing
342
* @param value - Whether to enable mock environment
343
*/
344
function setNgrxMockEnvironment(value: boolean): void;
345
346
/**
347
* Checks if NgRx is running in mock environment
348
* @returns True if in mock environment, false otherwise
349
*/
350
function isNgrxMockEnvironment(): boolean;
351
```
352
353
**Usage Examples:**
354
355
```typescript
356
// Type-safe action handling
357
interface AppState {
358
user: UserState;
359
todos: TodoState;
360
}
361
362
// Using StoreFeature for lazy loading
363
const userFeature: StoreFeature<UserState> = {
364
key: 'user',
365
reducers: userReducer,
366
reducerFactory: createReducerFactory(combineReducers),
367
initialState: { id: null, name: '', email: '' },
368
metaReducers: [loggingMetaReducer]
369
};
370
371
// Mock environment setup for testing
372
beforeEach(() => {
373
setNgrxMockEnvironment(true);
374
// Test setup...
375
});
376
377
afterEach(() => {
378
setNgrxMockEnvironment(false);
379
});
380
381
// Type validation at compile time
382
const validAction = increment(); // ✓ Valid
383
// const invalidAction = increment; // ✗ Compile error - CreatorsNotAllowedCheck
384
```