JS Built-ins
redux-legacyreducerbeginner

Reducer with Payload

πŸ“– Usage Example
function reducer(state = 0, action) {
  switch (action.type) {
    case 'ADD': return state + action.payload
    case 'SUBTRACT': return state - action.payload
    default: return state
  }
}
reducer(10, { type: 'ADD', payload: 5 })      // β†’ 15
reducer(10, { type: 'SUBTRACT', payload: 3 }) // β†’ 7

Using action.payload lets you pass dynamic values without creating a separate action type for every possible amount.

Reducer with Payload

Actions can carry extra data in a payload property. The reducer reads action.payload to perform dynamic updates:

{ type: 'ADD', payload: 5 }

This lets you dispatch one action type with different values rather than hard-coding the delta.

Challenge: Implement reducer(state = 0, action) that handles:

  • 'ADD' β†’ returns state + action.payload
  • 'SUBTRACT' β†’ returns state - action.payload
πŸ’‘ Hints (2)
  • β€’ Access the payload with `action.payload` inside the case body.
  • β€’ The payload convention is widely adopted in Redux β€” it keeps action shapes consistent.