Skip to content

QuizNot attempted

useMemo with empty deps and Math.random

Clicking the button 5 times — does the displayed number ever change, and how many times does 'recalculating' log in total?
function App() {
const expensiveValue = useMemo(() => {
console.log('recalculating');
return Math.random();
}, []);
const [, forceRender] = useState(0);
return (
<button onClick={() => forceRender(n => n + 1)}>
{expensiveValue}
</button>
);
}
1–4 to choose, Enter to submit
Show answer & explanation

Correct answer:

  • Number never changes after mount; logs 1 time total
  • With [] the memo computes once on mount and every later render reuses the cached Math.random() value, so the number never changes and the log fires once.
  • **Not 'changes each click
  • logs 6':** that is code without memoization.
  • Not 'logs 5': if it re-ran, the number would also change.
  • Not 'odd clicks': nothing alternates.
  • (React may discard memo caches in rare cases, so don't use useMemo for correctness.)