What is Reducer in NgRx: Explanation and Example
reducer is a pure function that takes the current state and an action, then returns a new state. It controls how the state changes in response to actions dispatched in the app.How It Works
Think of a reducer as a recipe that tells your app how to update its data when something happens. It receives the current state (like the current ingredients) and an action (like a cooking step), then returns a new state (the updated dish). This process is always predictable and does not change the original state directly.
Imagine you have a to-do list. When you add a new task, the reducer takes the existing list and the "add task" action, then creates a new list including the new task. This way, the app always knows exactly how the data changes, making it easier to track and debug.
Example
This example shows a simple reducer managing a counter state. It increases or decreases the count based on the action type.
import { createReducer, on } from '@ngrx/store'; import { createAction } from '@ngrx/store'; export const increment = createAction('[Counter] Increment'); export const decrement = createAction('[Counter] Decrement'); export const initialState = 0; export const counterReducer = createReducer( initialState, on(increment, state => state + 1), on(decrement, state => state - 1) );
When to Use
Use reducers in NgRx when you want to manage complex or shared state in an Angular app in a clear and predictable way. They are especially helpful when multiple parts of your app need to read or update the same data.
For example, use reducers to handle user authentication status, shopping cart contents, or any data that changes over time and affects the UI. This helps keep your app organized and easier to maintain.
Key Points
- A reducer is a pure function that returns a new state based on the current state and an action.
- Reducers never modify the existing state directly; they create a new state object.
- They help keep state changes predictable and easy to track.
- NgRx uses reducers to manage state in Angular apps following the Redux pattern.