reducerintermediatefunction 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.
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.