JS Built-ins
redux-legacyreducerintermediate

Array State β€” Adding Items

πŸ“– Usage Example
function reducer(state = [], action) {
  switch (action.type) {
    case 'ADD_ITEM': return [...state, action.payload]
    default: return state
  }
}
reducer(['a'], { type: 'ADD_ITEM', payload: 'b' }) // β†’ ['a', 'b']

Spread the existing array and append the new item to produce an immutable update.

Array State β€” Adding Items

When state is an array, never push directly (that would mutate state). Instead, use the spread operator to create a new array:

case 'ADD_ITEM': return [...state, action.payload]

This returns a brand-new array that includes all existing items plus the new one.

Challenge: Implement reducer(state = [], action) that handles 'ADD_ITEM' by returning a new array with the payload appended.

πŸ’‘ Hints (2)
  • β€’ `[...state, action.payload]` creates a new array without mutating the existing one.
  • β€’ Avoid `state.push()` β€” it mutates state in place, which breaks Redux's change detection.