reducerbeginnerfunction reducer(state = 0, action) {
switch (action.type) {
case 'INCREMENT': return state + 1
case 'DECREMENT': return state - 1
default: return state
}
}
reducer(5, { type: 'DECREMENT' }) // β 4A switch statement handles multiple action types cleanly; the default case ensures the reducer always returns a valid state.
When a reducer handles several action types, a switch statement keeps the code clean and readable:
switch (action.type) {
case 'INCREMENT': return state + 1
case 'DECREMENT': return state - 1
default: return state
}
The default case is essential β it handles unknown actions (including Redux's internal @@INIT).
Challenge: Implement reducer(state = 0, action) that handles 'INCREMENT', 'DECREMENT', and any other action via the default case.