Skip to content

QuizNot attempted

useMemo with a stable dependency

items prop reference never changes across renders. Clicking the button 3 times, how many times does 'computing total' log (including mount)?
function App({ items }) {
const [count, setCount] = useState(0);
const total = useMemo(() => {
console.log('computing total');
return items.reduce((a, b) => a + b, 0);
}, [items]);
return (
<div>
<p>{total}</p>
<button onClick={() => setCount(c => c + 1)}>{count}</button>
</div>
);
}
1–4 to choose, Enter to submit
Show answer & explanation

Correct answer:

  • 1
  • useMemo recomputes only when a dependency changes by Object.is
  • items keeps the same reference, so clicks re-render without recomputing: one log.
  • Not 3 or 4: re-renders alone don't invalidate a memo.
  • Not 0: it must compute once on mount.