Switch Statement Pattern
You'll learn how to organize multiple action handlers in a reducer using a switch statement for clean, readable logic.
Why Switch Statements?
When you have a reducer handling multiple action types, you need a way to route each action to the correct logic. While you could use a chain of if-else statements, the switch statement is the standard pattern that makes reducers clean and scannable.
The Basic Structure
A switch statement examines action.type and executes the matching case:
function reducer(state, action) {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
case 'DECREMENT':
return { count: state.count - 1 };
case 'RESET':
return { count: 0 };
default:
return state;
}
}
Why This Pattern Works
Think of the switch statement as a mail sorting office. Each action arrives with a type (like an address label), and the switch routes it to the right handler (mailbox). Each case is a dedicated handler for one action type.
The Default Case
Always include a default case that returns the current state unchanged. This handles:
- Typos in action types
- Unknown actions
- Initial reducer calls during setup
Without it, your reducer might return undefined and break your app.
Key Conventions
- Each case returns a new state object (immutable update)
- Action types are typically UPPERCASE strings
- Each case handles exactly one action type
Key Takeaway: The switch statement on action.type is the standard pattern for routing different actions to their handlers, with a default case ensuring safe fallback behavior.