In Redux, a reducer is one of the most important core concepts. Interviewers usually expect you to explain it clearly with its role in state management, purity, and immutability.
What is a Reducer in Redux?
A reducer is a pure function that determines how the application state changes in response to an action.
It takes two inputs:
-
Current state
-
Action
And returns:
-
New updated state
Signature:
(state, action) => newState
Simple Definition
A reducer in Redux is a pure function that receives the current state and an action, and returns a new state based on the action type.
Example of a Reducer
const initialState = { count: 0 };
function counterReducer(state = initialState, action) {
switch (action.type) {
case "INCREMENT":
return { count: state.count + 1 };
case "DECREMENT":
return { count: state.count - 1 };
default:
return state;
}
}
Key Characteristics of Reducers
1. Pure Function
-
Same input → same output
-
No API calls
-
No random values
-
No modifying external variables
2. Immutable Updates
-
Never modify existing state directly
-
Always return a new object
❌ Wrong:
state.count++;
return state;
✅ Correct:
return { ...state, count: state.count + 1 };
3. Based on Action Type
Reducers use action.type to decide what to do:
dispatch({ type: "INCREMENT" });
Why Reducers are Important in Redux?
-
Centralize state update logic
-
Make state changes predictable
-
Easier debugging and testing
-
Helps maintain large-scale applications
Real-World Analogy
Think of a reducer like a machine in a factory:
-
Input: raw material (state + action)
-
Process: rules (switch case logic)
-
Output: new product (new state)
Common Interview Questions Follow-up
Why is it called "reducer"?
Because it “reduces” multiple actions over time into a single final state.
Can reducers have side effects?
No. Reducers must be pure.
Side effects are handled by:
-
middleware like Redux Thunk
-
Redux Saga
Where are reducers used in Redux?
Reducers are combined and passed into the Redux store:
const store = createStore(counterReducer);
One-Line Interview Answer
A reducer in Redux is a pure function that takes the current state and an action, and returns a new state without mutating the original state.
