JS Built-ins
redux-legacyreducerbeginner

Multiple Action Types

πŸ“– Usage Example
function reducer(state = 0, action) {
  switch (action.type) {
    case 'INCREMENT': return state + 1
    case 'DECREMENT': return state - 1
    default: return state
  }
}
reducer(5, { type: 'DECREMENT' }) // β†’ 4

A switch statement handles multiple action types cleanly; the default case ensures the reducer always returns a valid state.

Multiple Action Types

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.

πŸ’‘ Hints (2)
  • β€’ A switch statement is idiomatic Redux β€” each `case` handles one action type.
  • β€’ Always include a `default: return state` to handle any action you haven't handled explicitly.