Skip to content

QuizNot attempted

useReducer lazy init

Clicking the button 3 times, how many total times does 'lazy init' log?
function init(initialCount) {
console.log('lazy init');
return { count: initialCount };
}
function reducer(state, action) {
return action.type === 'inc' ? { count: state.count + 1 } : state;
}
function App({ start }) {
const [state, dispatch] = useReducer(reducer, start, init);
return <button onClick={() => dispatch({ type: 'inc' })}>{state.count}</button>;
}
1–4 to choose, Enter to submit
Show answer & explanation

Correct answer:

  • 1
  • The third argument init is called once on mount as init(start)
  • later dispatches and re-renders reuse the stored state, so it logs once.
  • Not 3 or 4: init isn't called per render or per dispatch.
  • Not 0: it must run to produce the initial state.