Skip to content

QuizNot attempted

Lazy initializer runs once

Clicking the button 3 times — how many times does 'initializer ran' log in total?
function Counter() {
const [count, setCount] = useState(() => {
console.log('initializer ran');
return 0;
});
return <button onClick={() => setCount(count + 1)}>{count}</button>;
}
1–4 to choose, Enter to submit
Show answer & explanation

Correct answer:

  • 1
  • Passing a function (useState(() => ...)) tells React to call it only on the initial render
  • later renders ignore it, so it logs once.
  • Not 0: it must run once to produce the initial value.
  • Not 3 or 4: that would happen with useState(compute()), which evaluates on every render (the result is just ignored).