A reducer in Redux is a pure function that takes the previous state and an action, and returns the next state. Essentially, a reducer determines how your application's state changes in response to an action dispatched to the Redux store.
Key aspects of reducers in Redux:
1. Purity: Reducers should be pure functions, meaning they should not modify their arguments or have side effects. They should return a new state object rather than modifying the existing one.
2. Using switch: Typically, reducers use a switch statement to handle different action types. Each case inside the switch handles a specific action type and returns the corresponding state change.
Here's an example of a simple reducer in Redux:
const initialState = {
count: 0
};
const counterReducer = (state = initialState, action) => {
switch (action.type) {
case 'INCREMENT':
return { ...state, count: state.count + 1 };
case 'DECREMENT':
return { ...state, count: state.count - 1 };
default:
return state;
}
};In this example, counterReducer is a reducer that manages the state change of a counter based on the action type. It takes the previous state state and the action action, and returns a new state depending on the action type.
Comments