Skip to content

QuizNot attempted

Sequential dispatches compound

After one click, what does the button show?
function reducer(state, action) {
switch (action.type) {
case 'inc': return { count: state.count + 1 };
default: return state;
}
}
function App() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
const handleClick = () => {
dispatch({ type: 'inc' });
dispatch({ type: 'inc' });
};
return <button onClick={handleClick}>{state.count}</button>;
}
1–4 to choose, Enter to submit
Show answer & explanation

Correct answer:

  • 2
  • Each dispatch queues an action, and the reducer receives the state produced by the previous queued action, exactly like a functional updater, so two inc actions compound: 0→1→2.
  • Not 1: that is the stale setCount(count + 1) pattern
  • reducers don't read render-time values.
  • Not 0: both dispatches apply on the next render.
  • Not NaN: state.count is a number.