useMemo & useCallback — React

Every render runs all the code in the component again. useMemo(() => calculate(n), [n]) remembers the value of a heavy calculation, and only calculates it…

You type into a search box, and every letter appears late, as if the keyboard were stuck. The cause often isn't the box at all, but some heavy calculation elsewhere in the same component that runs again on every keystroke.

Every time state changes, React runs your component function again from the top (a re-render). Everything inside it runs again too: calculations, creating objects, and creating functions. Usually all of that is fast and fine. useMemo and useCallback are two ways to remember something from the previous render, so that thing isn't made again when the values used to make it haven't changed. It's like a cashier who has just calculated the total of a long shopping list. If the customer only asks "what was the total again?", the cashier reads the note instead of adding every item again. The cashier only calculates again when what's in the basket changes. In React, calculating the total is the heavy calculation, the note is the remembered value, and what's in the basket is the dependency: a value that makes the calculation run again when it changes.

Every render runs all the code again

This component has a slow calculation, factorial, and a text field:

function factorial(n) {
  const end = performance.now() + 80 // fake load: 80 ms
  while (performance.now() < end) {}
  let product = 1
  for (let i = 2; i <= n; i++) product *= i
  return product
}

function App() {
  const [n, setN] = useState(5)
  const [text, setText] = useState("")
  const result = factorial(n)

  return (
    <div>
      <p>{n}! = {result}</p>
      <input value={text} onChange={(e) => setText(e.target.value)} />
    </div>
  )
}

Take a guess first: you type test into the text field, which has nothing to do with n. Without useMemo, how many times is factorial calculated again? (The Increase n button in the last row of the table adds one to n. Its code is in the Child example below.)

Event App render no. factorial runs, without useMemo factorial runs, with useMemo
first show 1 1 1
type t 2 2 1
type e 3 3 1
type s 4 4 1
type t 5 5 1
click Increase n, n becomes 6 6 6 2

Typing test means 4 new renders. Without useMemo, the calculation runs again on each of those renders, so 4 times: 4 × 80 ms = 320 ms of slow typing.

useMemo: remember a calculated result

Wrap the calculation in useMemo:

const result = useMemo(() => factorial(n), [n])

useCallback: remember the function itself

Functions are made new on every render too. const handleAdd = () => setN((c) => c + 1) produces a new function each time. Two functions with the same body still count as different: (() => {}) === (() => {}) is false. Usually that's no problem. The problem only starts when that function is passed as a prop to a component wrapped in memo.

memo(Component) makes a component skip its re-render when all its props are the same as in the previous render. The details are in the next lesson, React.memo. For now, just know this: when a prop is a new function, memo treats the props as changed.

In this example, Child is wrapped in memo and gets handleAdd through the prop onAdd:

const Child = memo(function Child({ onAdd }) {
  console.log("Child rendered")
  return <button onClick={onAdd}>Increase n</button>
})

function App() {
  const [n, setN] = useState(5)
  const [text, setText] = useState("")
  const result = useMemo(() => factorial(n), [n])
  const handleAdd = useCallback(() => setN((c) => c + 1), [])

  return (
    <div>
      <p>{n}! = {result}</p>
      <Child onAdd={handleAdd} />
      <input value={text} onChange={(e) => setText(e.target.value)} />
    </div>
  )
}
Child wrapped in memo? handleAdd uses useCallback? When you type
no no Child renders again
no yes Child renders again, the useCallback is wasted
yes no Child renders again, because its prop is a new function
yes yes Child is skipped

When you don't need them

⚠️ Memos that never update, or make no difference at all

TL;DR: Every render runs all the code in the component again. useMemo(() => calculate(n), [n]) remembers the value of a heavy calculation, and only calculates it again when a dependency (a value in the array [n]) changes. useCallback(fn, deps) remembers the function itself, the same as useMemo(() => fn, deps). useCallback only helps when that function is passed to a child wrapped in memo (which skips its re-render when its props are the same). Write the dependencies in full, and use an updater function such as setN((c) => c + 1) so useCallback doesn't read old state. Cheap calculations and children without memo need neither. In projects with the React Compiler (a build tool from the React team), the compiler remembers calculated results and functions automatically.

⚡ Every render runs all the code again

Guess first: the component App has a heavy calculation, factorial(n) (80 ms), in its body, and a text field. You type test into that text field, which has nothing to do with n. Without useMemo, how many times is factorial calculated again?

Four times, once per letter. Every keystroke causes a render, and every render runs all the code in the component again: 4 × 80 ms = 320 ms of slow typing.

Meaning: Every keystroke changes state, then React renders again. A heavy calculation in the component body runs on every render, even when n didn't change.

⚡ useMemo: remember the result

Write:

const result = useMemo(() => factorial(n), [n])

Meaning: useMemo takes a function that does the calculation and a dependency array [n] (the values the calculation uses). React remembers the result, and only calculates it again when n changes. Typing in the text field doesn't change n, so the old result is used again.

⚡ useCallback: remember the function

Write:

const handleAdd = useCallback(() => setN((c) => c + 1), [])

Meaning: Without useCallback, handleAdd is a new function on every render. The dependency array is empty ([]), because setN((c) => c + 1) uses an updater function and doesn't need to read n. useMemo remembers the value its function returns, while useCallback remembers the function itself. useCallback only helps when handleAdd is passed as a prop to a child wrapped in memo, which is a component that skips its re-render when its props are the same.

What you will learn