Skip to content
ClapelloNotes by Barath
ReactCh 09 · 6/6
Deep dive5 min readUpdated

React / 51

useMemo and useCallback

TL;DR

useMemo caches a calculated value between renders; useCallback caches a function. Use them for slow calculations and stable props, not everywhere.

Same value vs same object

5 === 5

numbers compare by value

same ✓
"veg" === "veg"

so do strings and booleans

same ✓
{} === {}

two different objects

new ✗
[] === []

two different arrays

new ✗
(() => {}) === (() => {})

two different functions

new ✗
useMemo / useCallback result

same object until a dependency changes

same ✓
Every render creates new objects and functions, so to memo they look 'changed' even when the contents are identical. useMemo and useCallback hand back the same one.

This is the whole reason these hooks exist. React compares props and dependencies with Object.is. Numbers and strings compare by value; objects, arrays and functions compare by identity: "is this the very same thing in memory?". A new {} each render is never the same thing.

useMemo: cache a calculation

Menu.jsx
import { useMemo, useState } from "react";
 
export default function Menu({ items }) {
  const [query, setQuery] = useState("");
  const [cart, setCart] = useState([]);
  const visible = useMemo(
    () => items.filter((i) => i.name.toLowerCase().includes(query.toLowerCase())),
    [items, query]
  );
  // …
}

On the first render, React runs the function and stores the result. On later renders, if items and query are the same as last time, it hands back the stored array without filtering again. Adding to the cart re-renders Menu, but visible is reused.

useCallback: cache a function

useCallback(fn, deps) gives you the same function on every render until a dependency changes. It's shorthand for useMemo(() => fn, deps). Here's the whole menu, with both hooks feeding a memo child:

Menu.jsx
import { memo, useCallback, useMemo, useState } from "react";
 
const MenuList = memo(function MenuList({ items, onAdd }) {
  return items.map((i) => <button key={i.id} onClick={() => onAdd(i)}>{i.name}</button>);
});
 
export default function Menu({ items }) {
  const [query, setQuery] = useState("");
  const [cart, setCart] = useState([]);
 
  const visible = useMemo(
    () => items.filter((i) => i.name.toLowerCase().includes(query.toLowerCase())),
    [items, query]
  );
  const handleAdd = useCallback((item) => setCart((c) => [...c, item]), []);
 
  return (
    <>
      <input value={query} onChange={(e) => setQuery(e.target.value)} />
      <p>{cart.length} in cart</p>
      <MenuList items={visible} onAdd={handleAdd} />
    </>
  );
}

Click a dish: cart changes and Menu re-renders. But visible is the same array (items and query didn't change) and handleAdd is the same function (its dependency list is empty, and a state setter never changes). So MenuList gets identical props and skips its render. Remove either hook and it re-renders on every click.

When they help, and when they don't

HelpsDoesn't help
A calculation that's measurably slow (React's docs suggest timing it: around 1 ms or more is worth a look)Cheap work: a + b, a short .map(), formatting a string
A value or function passed to a memo childProps passed to a child that isn't wrapped in memo (it re-renders anyway)
A value or function used as a useEffect dependency, so the effect doesn't re-run every renderEverywhere "just in case": it adds code, and the cache itself has a cost

Don't

Memoize everything

const total = useMemo(() => price * qty, [price, qty]);
const label = useMemo(() => `${qty} items`, [qty]);
const onClick = useCallback(() => setOpen(true), []);
// passed to a plain <button>: no benefit

Do

Memoize what you measured

const total = price * qty;
const label = `${qty} items`;
const visible = useMemo(
  () => filterAndSort(items, query), // slow: 5,000 items
  [items, query]
);

Gotchas

Recall

Can you answer these?

0/4

Answer out loud (or in your head) before you tap. That's what makes it stick.

Saved on this device only. No login.