useMemo: Caching a Calculation

Keep a slow calculation from running on every render. Toggle the theme and it is skipped; change n and it runs.

React · intermediate · 7 min · 28 steps · free

What you'll learn

UseMemo.jsx

import { useMemo, useState } from 'react';

function slowSquare(n) {
  console.log(`calculating ${n}²`);
  return n * n;
}

export default function Calculator() {
  const [n, setN] = useState(4);
  const [dark, setDark] = useState(false);
  const square = useMemo(() => slowSquare(n), [n]);

  return (
    <div className={dark ? 'dark' : 'light'}>
      <p>{n}² = {square}</p>
      <button onClick={() => setDark(!dark)}>Toggle theme</button>
      <button onClick={() => setN(n + 1)}>n + 1</button>
    </div>
  );
}

Step by step

  1. React renders <Calculator> for the first time: it calls the Calculator function.
  2. useState runs for the first time, so React stores the starting value for n and returns it: 4.
  3. useState runs for the first time, so React stores the starting value for dark and returns it: false.
  4. Prints “calculating 4²”.
  5. slowSquare returns 16.
  6. On the first render useMemo has nothing cached, so it calls the calculation.
  7. useMemo gives square = 16. It only recalculates when a dependency changes.
  8. Calculator returns JSX: a description of what the screen should show, <div className="light">…</div>. React has not changed the page yet.
  9. React turns the JSX into real page elements and shows them: look at the Screen panel.
  10. You toggle the theme. Only dark changes.
  11. setDark(!dark) does not change dark right away: React queues the update and will render again. In this call dark is still false.
  12. React renders <Calculator> again (render 2): it calls Calculator once more, from the top.
  13. useState returns the value React has kept for n: 4. The starting value is only used on the first render.
  14. useState returns the value React has kept for dark: true. The starting value is only used on the first render.
  15. useMemo checks [n]: still 4, so it returns the cached 16 without calling slowSquare.
  16. Calculator returns JSX: a description of what the screen should show, <div className="dark">…</div>. React has not changed the page yet.
  17. React compares the new JSX with the last one and updates only what changed on the page.
  18. You click n + 1.
  19. setN(n + 1) does not change n right away: React queues the update and will render again. In this call n is still 4.
  20. React renders <Calculator> again (render 3): it calls Calculator once more, from the top.
  21. useState returns the value React has kept for n: 5. The starting value is only used on the first render.
  22. useState returns the value React has kept for dark: true. The starting value is only used on the first render.
  23. n changed to 5, so useMemo calls the calculation again.
  24. slowSquare returns 25.
  25. The calculation returns 25; useMemo remembers it.
  26. useMemo gives square = 25. It only recalculates when a dependency changes.
  27. Calculator returns JSX: a description of what the screen should show, <div className="dark">…</div>. React has not changed the page yet.
  28. 5² = 25. The Output shows the calculation ran only twice in three renders.

Common mistakes

Best practices

Key takeaways

Check yourself

useMemo(() => f(a), [a]): when does f run?

Answer: When a changes

What does useMemo return?

Answer: The value. useCallback returns the function.

·

More in Performance