HardHooks & Closures💻 Output Question

useReducer — dispatch queues actions, reducer is pure

💡

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.

What does this output?

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]);

Correct Output

a,b
1
d

Why this output?

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.

Practice predicting output live →

66 output questions with instant feedback

💻 Try Output Quiz