When to Use useMemo and useCallback in React

Skipping repeated work in React components with useMemo and useCallback.

When a React component re-renders, everything inside it runs again. Most of the time that's fast and you don't need to think about it. But when a calculation is slow, or a function gets recreated on every render and causes other code to run, useMemo and useCallback let you skip the repeated work.

TL;DR useMemo remembers a value. useCallback remembers a function. Both only recompute when something in their dependency array changes.

useMemo

Pass useMemo a function that calculates a value, and a list of dependencies. It runs the function on the first render, then only again when a dependency changes:

import React, { useState, useMemo } from "react"
function ProductList({ products }) {
const [query, setQuery] = useState("")
const [darkMode, setDarkMode] = useState(false)
const filtered = useMemo(() => {
return products.filter((product) =>
product.name.toLowerCase().includes(query.toLowerCase())
)
}, [products, query])
return (
<div className={darkMode ? "dark" : "light"}>
<input value={query} onChange={(e) => setQuery(e.target.value)} />
<button onClick={() => setDarkMode(!darkMode)}>Toggle theme</button>
<ul>
{filtered.map((product) => (
<li key={product.id}>{product.name}</li>
))}
</ul>
</div>
)
}

Without useMemo, toggling the theme would filter the whole product list again. With it, the list is only filtered when products or query change.

useCallback

Every render creates brand new functions, even if their code is the same. That matters when a function is in a dependency array, because a new function counts as a change:

import React, { useState, useEffect, useCallback } from "react"
function SearchResults({ query }) {
const [results, setResults] = useState([])
const fetchResults = useCallback(async () => {
const res = await fetch(`/api/search?q=${query}`)
setResults(await res.json())
}, [query])
useEffect(() => {
fetchResults()
}, [fetchResults])
return (
<ul>
{results.map((result) => (
<li key={result.id}>{result.title}</li>
))}
</ul>
)
}

useCallback hands back the same fetchResults function until query changes. Without it, the effect would see a new function on every render, run again, set state, re-render and fetch again in a loop.

useCallback(fn, deps) is the same as useMemo(() => fn, deps). It's just a shorter way to write it for functions.

When Not to Bother

Both hooks have a small cost of their own, so wrapping everything doesn't make an app faster. Reach for them when:

  • A calculation is noticably slow, like filtering or sorting a big list.
  • A value or function is used in another hook's dependency array.
  • A function is passed to a child component wrapped in React.memo.

If you're not sure, leave them out and use the Profiler in the React DevTools to find what's actually slow.

Have some feedback on this post? .