Return Value: Next State
You'll learn why a reducer function must return a new state object and how that triggers React's re-rendering mechanism.
The Final Piece: What the Reducer Gives Back
You've learned that a reducer takes (state, action) as parameters. Now comes the crucial part: the reducer must return the next state. This return value is what React uses to determine if the UI needs to update.
Think of the reducer like a vending machine: you put in your current inventory (state) and a selection button (action), and it must give you back the updated inventory. If it returns nothing, or returns something invalid, the vending machine breaks.
Why This Matters for React
React compares the returned state object to the previous one. If they're different references (a new object), React knows it needs to re-render your component with the updated state. This is the trigger for UI updates.
function counterReducer(state, action) {
switch (action.type) {
case 'INCREMENT':
// ✅ Returns a NEW state object
return { count: state.count + 1 };
case 'DECREMENT':
// ✅ Returns a NEW state object
return { count: state.count - 1 };
case 'RESET':
// ✅ Returns a NEW state object
return { count: 0 };
default:
// ✅ No change needed? Return current state
return state;
}
}
The Default Case
Always include a default case that returns the current state unchanged. This handles any unknown actions gracefully without breaking your component.
Key Takeaway: The reducer's return value becomes your component's next state—React uses this new object reference to trigger re-renders, making your UI reflect the state change.