MediumHooks & Closures💻 Output Question

useState initializer runs only once

💡

Hint

useState(() => expensiveComputation()) — the function form is only called once on mount. Passing the value directly (useState(expensiveComputation())) calls it on every render.

What does this output?

// Simulates useState lazy initialization
function useState(init) {
  let state = typeof init === 'function' ? init() : init;
  return [
    () => state,
    (newVal) => { state = typeof newVal === 'function' ? newVal(state) : newVal; }
  ];
}

let initCallCount = 0;
const expensiveInit = () => {
  initCallCount++;
  return 42;
};

// Called like useState(() => expensiveInit())
const [getState, setState] = useState(expensiveInit);

console.log(getState());
console.log(initCallCount);  // should be 1

setState(v => v + 1);
console.log(getState());
console.log(initCallCount);  // still 1 — init not re-run

Correct Output

42
1
43
1

Why this output?

Explanation: The initializer function is called once at creation. setState doesn't re-run the init function. initCallCount stays at 1.

Key Insight: useState(() => expensiveComputation()) — the function form is only called once on mount. Passing the value directly (useState(expensiveComputation())) calls it on every render.

Practice predicting output live →

66 output questions with instant feedback

💻 Try Output Quiz