What is NgRx in Angular: State Management Explained
NgRx is a library for managing state in Angular applications using a pattern called Redux. It helps keep your app data predictable and organized by using actions, reducers, and a centralized store.How It Works
Imagine your Angular app as a busy office where many people need to share information clearly and quickly. NgRx acts like a well-organized filing system in that office. Instead of everyone keeping their own notes, all important data is stored in one central place called the store.
When something changes, like a user clicking a button, an action is sent to the store describing what happened. Then, a reducer listens to these actions and decides how to update the store’s data. This way, the app’s state changes are predictable and easy to follow, just like having a clear record of all office updates.
Example
This example shows a simple counter using NgRx. The counter can be increased or decreased by dispatching actions, and the store keeps track of the current count.
import { createAction, createReducer, on } from '@ngrx/store'; import { Component } from '@angular/core'; import { Store, StoreModule } from '@ngrx/store'; // Actions export const increment = createAction('[Counter] Increment'); export const decrement = createAction('[Counter] Decrement'); // Initial state export const initialState = 0; // Reducer export const counterReducer = createReducer( initialState, on(increment, state => state + 1), on(decrement, state => state - 1) ); @Component({ selector: 'app-counter', template: ` <button (click)="decrement()">-</button> <span>{{ count$ | async }}</span> <button (click)="increment()">+</button> ` }) export class CounterComponent { count$ = this.store.select('count'); constructor(private store: Store<{ count: number }>) {} increment() { this.store.dispatch(increment()); } decrement() { this.store.dispatch(decrement()); } } // In your AppModule imports: // StoreModule.forRoot({ count: counterReducer })
When to Use
Use NgRx when your Angular app has complex state that many parts of the app need to share or update. It is especially helpful in large apps where keeping track of data changes can get confusing.
For example, if you have a shopping cart, user login status, or data from a server that many components use, NgRx helps keep everything in sync and easy to debug.
Key Points
- NgRx uses a central store to hold app state.
- Actions describe events that change state.
- Reducers update state based on actions.
- Helps keep state predictable and easy to debug.
- Best for medium to large Angular apps with shared state.