In NgRx, Reducer, Action and State are core concepts used to implement state management of applications. The following is an explanation and understanding of these concepts:
Reducer:
Definition: Reducer is a pure function that accepts the current state (state) and an action as parameters, and then returns a new state. It is used to handle changes in application state.
Role: Reducer defines how to respond to various operations (actions) to change the state of the application. It is responsible for calculating the value of the new state.
Example:
function counterReducer(state: number, action: any): number {
switch (action.type) {
case 'INCREMENT':
return state + 1;
case 'DECREMENT':
return state - 1;
default:
return state;
}
}
Action:
Definition: Action is an ordinary JavaScript object that describes what happened. It contains at least one type attribute, used to identify the type of action.
Function: Actions are events that trigger state changes. They are passed to the Reducer to tell the Reducer how to handle state changes.
Example:
const incrementAction = {
type: 'INCREMENT' };
const decrementAction = {
type: 'DECREMENT' };
State:
Definition: State is a JavaScript object that represents the current state of the application. It contains application data and status information.
Function: State saves application data, including user interface status, user input, application configuration, etc. State is usually immutable, and a new state object is created every time a state change occurs.
Example:
const initialState = {
count: 0,
loggedIn: false,
};
In NgRx, these concepts work together. When an Action is dispatched, the Reducer handles the state change based on the Action type and returns a new state. This one-way data flow ensures state predictability and controllability, making state management easier. In a large application, there can be multiple Reducers and multiple Actions to manage the state and operations of different parts.