Hint
useState(() => expensiveComputation()) — the function form is only called once on mount. Passing the value directly (useState(expensiveComputation())) calls it on every render.
// 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-run42 1 43 1
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.