A reducer is a pure function that takes the current state and an action as arguments and returns a new state based on the action type. It determines how the state changes in response to a given action. Reducers are crucial in Redux because they define the logic for handling state updates, ensuring that the state is modified in a predictable way without directly mutating the original state.
function counterReducer(state = { count: 0 }, action) {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
case 'DECREMENT':
return { count: state.count - 1 };
default:
return state;
}
}