reducerintermediatefunction reducer(state = { user: { name: '', age: 0 } }, action) {
switch (action.type) {
case 'SET_NAME':
return { ...state, user: { ...state.user, name: action.payload } }
default: return state
}
}
reducer(undefined, { type: 'SET_NAME', payload: 'Alice' })
// β { user: { name: 'Alice', age: 0 } }Spread each level of nesting to produce a completely new object tree without mutating any existing reference.
Updating nested state immutably requires spreading each level of the object:
case 'SET_NAME':
return { ...state, user: { ...state.user, name: action.payload } }
First spread the root state to preserve other top-level keys, then spread the nested object to preserve its other keys, finally override only the changed property.
Challenge: Implement reducer with default state { user: { name: '', age: 0 } } that handles 'SET_NAME' and 'SET_AGE'.