Hint
Reducers must be pure — no side effects, no mutation of the previous state. Each dispatch creates a new state object. This is what makes time-travel debugging possible.
function reducer(state, action) {
switch (action.type) {
case 'ADD': return { ...state, items: [...state.items, action.payload] };
case 'CLEAR': return { ...state, items: [] };
default: return state;
}
}
let state = { items: [] };
const dispatch = (action) => { state = reducer(state, action); };
dispatch({ type: 'ADD', payload: 'a' });
dispatch({ type: 'ADD', payload: 'b' });
console.log(state.items.join(','));
dispatch({ type: 'ADD', payload: 'c' });
dispatch({ type: 'CLEAR' });
dispatch({ type: 'ADD', payload: 'd' });
console.log(state.items.length);
console.log(state.items[0]);a,b 1 d
Explanation: After two ADDs: ['a','b']. After ADD 'c', CLEAR, ADD 'd': only ['d'] remains. The reducer is pure — each call returns a new state object.
Key Insight: Reducers must be pure — no side effects, no mutation of the previous state. Each dispatch creates a new state object. This is what makes time-travel debugging possible.