React useMemo and useCallback: When to Use Them
Learn when useMemo and useCallback help React rendering, when they add work, and what React Compiler changes about manual memoization.
Overview
useMemo caches the result of a calculation between renders. useCallback caches a function definition. They help when a repeated calculation is expensive or when a new function reference prevents a memoized child from skipping work. Neither hook makes the first render faster, and neither should be needed for correctness.
Profile the slow interaction before adding either hook. The React performance guide covers profiling and other causes of slow rendering.
When to Use
- Repeated expensive calculations: cache a costly filter or sort only if the input data stays identical across renders caused by other parts of the UI.
- Callbacks passed to memoized children: a stable callback reference can let a
React.memochild skip a render when the rest of its props are unchanged. - Objects sent to memoized children: a
React.memochild shallowly compares object props too. Cache the object only when a fresh reference is what makes that child redo work. - Context provider values: keep the provider’s object stable when the provider renders for an unrelated reason, such as a state toggle that the value doesn’t use.
When NOT to Use
Skip the hooks for a sum or small transformation unless profiling shows a reason to keep them. Passing a new callback to an ordinary DOM element or an un-memoized child won’t stop that child from rendering with its parent. When a helper is used only by an Effect, keep the helper inside that Effect. Never make correctness depend on a memo cache.
Solution
Basic useMemo for expensive computation
import { useMemo, useState } from "react";
function ProductList({ products }) {
const [query, setQuery] = useState("");
const [sort, setSort] = useState("name");
const [showPrices, setShowPrices] = useState(true);
const filteredSorted = useMemo(() => {
const filtered = products.filter((p) =>
p.name.toLowerCase().includes(query.toLowerCase())
);
return filtered.sort((a, b) => {
if (sort === "name") return a.name.localeCompare(b.name);
if (sort === "price") return a.price - b.price;
return 0;
});
}, [products, query, sort]);
return (
<div>
<input value={query} onChange={(e) => setQuery(e.target.value)} />
<select value={sort} onChange={(e) => setSort(e.target.value)}>
<option value="name">Name</option>
<option value="price">Price</option>
</select>
<button onClick={() => setShowPrices((value) => !value)}>
Toggle prices
</button>
<ul>
{filteredSorted.map((p) => (
<li key={p.id}>
{p.name} {showPrices && `— $${p.price}`}
</li>
))}
</ul>
</div>
);
}
Changing query or sort needs a fresh list, so the memo won’t remove that work on a keystroke. It can reuse the old list when an unrelated change, such as hiding prices, renders ProductList while products, query, and sort still point to the same data. Keep the products reference stable if its contents haven’t changed. If rendering the resulting rows is the bottleneck, virtualize the list rather than adding more memo hooks.
useCallback for stable function references
import { useCallback, useState, memo } from "react";
const MemoizedChild = memo(function MemoizedChild({ onClick, id }) {
console.log("MemoizedChild rendered");
return <button onClick={() => onClick(id)}>Click me</button>;
});
function Parent() {
const [count, setCount] = useState(0);
const [text, setText] = useState("");
const handleClick = useCallback((id) => {
console.log("Clicked item", id);
}, []);
return (
<div>
<input value={text} onChange={(e) => setText(e.target.value)} />
<button onClick={() => setCount(count + 1)}>Count: {count}</button>
<MemoizedChild onClick={handleClick} id={1} />
</div>
);
}
Typing or changing the count renders Parent. A fresh handleClick on every render gives MemoizedChild a different prop even when id stayed the same, so the child can’t use memoization. With useCallback, the callback reference survives those unrelated renders and the child can skip them. The log is there to observe renders during development, not to simulate expensive work.
When useCallback is unnecessary
import { useState } from "react";
function Parent() {
const [text, setText] = useState("");
// This child is NOT memoized — it re-renders on every parent render anyway
const handleClick = (id) => {
console.log("Clicked", id);
};
return (
<div>
<input value={text} onChange={(e) => setText(e.target.value)} />
<button onClick={() => handleClick(1)}>Click</button>
</div>
);
}
Wrapping handleClick in useCallback here adds work without helping: the button isn’t a memoized component.
useMemo for context value stabilization
import { createContext, useContext, useMemo, useState } from "react";
const UserContext = createContext(null);
const ThemeContext = createContext("light");
function UserProvider({ children }) {
const [user, setUser] = useState(null);
const [theme, setTheme] = useState("light");
const value = useMemo(
() => ({ user, setUser }),
[user, setUser]
);
return (
<UserContext.Provider value={value}>
<ThemeContext.Provider value={theme}>
<button onClick={() => setTheme((value) =>
value === "light" ? "dark" : "light"
)}>
Toggle theme
</button>
{children}
</ThemeContext.Provider>
</UserContext.Provider>
);
}
function UserProfile() {
const { user } = useContext(UserContext);
return <div>{user?.name}</div>;
}
Context consumers re-render when their provider’s value changes under Object.is. In this example, the memoized UserContext object stays the same while ThemeContext receives a new theme, so UserProfile isn’t notified through UserContext. That doesn’t make UserProfile immune to renders caused by its own props, state, or parent. When different groups of consumers need different update schedules, separate their contexts; the React state management guide explains how to split the state.
Measuring with React Profiler
import { Profiler } from "react";
function onRender(id, phase, actualDuration) {
console.log(`${id} ${phase} took ${actualDuration}ms`);
}
function App() {
return (
<Profiler id="ProductList" onRender={onRender}>
<ProductList products={largeProductList} />
</Profiler>
);
}
Run the same interaction in React DevTools Profiler before and after adding the hook. Compare which components committed, then decide whether the saved work matters to that interaction. Device speed, data size, and the rest of the render all shape the result, so a fixed millisecond threshold is misleading. If profiling shows no useful improvement, remove the cache.
Explanation
React checks each dependency against its previous value with Object.is. With unchanged inputs, useMemo returns its stored result and useCallback returns its stored function. Once one dependency differs, React computes a new value or a new function. Declare every reactive value the calculation reads; a missing one can hold onto a stale result or closure.
The calculation inside useMemo has to stay pure and synchronous. Because React may discard a cache in specific situations, the component must remain correct without it. Treat props and state as immutable: mutating an object in place can keep the same reference and prevent React from seeing the change.
When React Compiler is enabled in the build, it can memoize values and functions automatically. Check whether the project uses it before adding manual hooks. It covers routine memoization, but profiling still decides whether a remaining optimization matters.
Keep Effect helpers inside the Effect
import { useEffect, useState } from "react";
function SearchResults({ query }) {
const [results, setResults] = useState([]);
const [error, setError] = useState("");
useEffect(() => {
const controller = new AbortController();
setError("");
fetch(`/api/search?q=${encodeURIComponent(query)}`, {
signal: controller.signal,
})
.then((response) => {
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return response.json();
})
.then((payload) => setResults(payload.items))
.catch((cause) => {
if (cause.name !== "AbortError") setError(cause.message);
});
return () => controller.abort();
}, [query]);
return error ? (
<p role="alert">{error}</p>
) : (
<ul>
{results.map((result) => (
<li key={result.id}>{result.name}</li>
))}
</ul>
);
}
Assume the endpoint returns an items array with id and name fields. Keep the fetch work inside the Effect and list every value the request reads as a dependency. React’s useEffect documentation covers this pattern: a helper declared inside the Effect doesn’t need to sit in the dependency list. Reserve useCallback for functions that are shared with code that compares function identity.
Variants
Choose the hook that matches the work shown in the Profiler.
Cache a calculation with useMemo
The product example caches the filtered and sorted array. React reuses it on an unrelated state change, but recalculates it when products, query, or sort changes.
Keep a function reference with useCallback
The callback example passes handleClick to a memoized child. As long as the callback and the child’s other props keep the same references, a render triggered by typing or the count can skip MemoizedChild.
Skip a child render with React.memo
React.memo only makes the prop comparison shallow. The child still renders when its own state or a consumed context changes, and any new object or callback prop counts as a change.
Best Practices
- Profile a representative interaction before adding memoization, then compare the same interaction afterward.
- List every reactive input in the dependency array. Fix stale closures instead of hiding them with an empty array.
- Choose
useCallbackwhen a memoized child or an API actually compares function identity. - Keep arrays and objects immutable. A stable reference only helps while the underlying data is unchanged.
- If React Compiler is enabled, check its output and diagnostics before adding manual caches.
Common Mistakes
Memoization doesn’t make a cheap expression worthwhile. Writing useMemo(() => a + b, [a, b]) costs more code than simply calculating a + b.
An empty dependency list captures the initial values. If a calculation reads x, useMemo(() => compute(x), []) keeps using the first x; include it in the dependency list so React can refresh the result.
An array recreated by a parent gets a new identity even when its elements look identical, so a child calculation depending on that array runs again. Keep the data immutable, and stabilize the input where it’s created only when measurements justify the extra cache.
Memoizing a context value doesn’t suppress updates when that value changes. Split contexts if consumers need independent updates. React can also discard a memoized value, so use state or a ref when the value is required for correctness.
Troubleshooting
A memoized child still renders
Compare each prop against the previous render. A new object, array, or callback defeats the shallow comparison. The child also renders when its own state or a consumed context changes.
An Effect runs after every render
Inspect the dependency list first. When a helper exists only for that Effect, declare it inside the Effect. If other code shares it, stabilize the function only when its identity matters.
The calculation runs while typing
Typing a different query needs a fresh result. useMemo skips the calculation only when none of its dependencies changed.
The cached result looks stale
Check for an omitted dependency or an in-place mutation, then enable the React Hooks lint rules. Don’t omit a dependency to force reuse.
Further Reading
The React Compiler guide explains automatic memoization when the compiler is enabled.
Frequently Asked Questions
Does useMemo guarantee that React keeps the cached value?
No. React may drop a cached value in specific situations, so use useMemo only to improve performance. The component must still return the correct result without the cache.
When does useCallback help a child component?
It helps a child wrapped in React.memo when the callback is the only prop that would otherwise change while the other props stay equal. A regular DOM button or an un-memoized child gains nothing from it.
Why can a memoized component still render?
React.memo compares only props. It doesn't block updates caused by the component's state or context, and a newly created object or function prop still counts as a change.
Can React Compiler replace every manual memo?
When enabled, React Compiler can add memoization for values and functions it can safely analyze. Check the project's compiler setup and profile the result. Some identity requirements or code the compiler can't optimize may still need manual handling.
What should I do with asynchronous work?
useMemo runs a synchronous, pure calculation. Start requests in an Effect or use a data-fetching library; don't put a promise or side effect in the memo callback.
Related Resources
Complete Guide to React Performance Optimization
Optimize React apps for speed. Covers memoization, virtualization, code splitting, bundle analysis, React Profiler, concurrent features, and Core Web Vitals.
GuideReact State Management: Zustand, Jotai, TanStack Query
How to choose and combine React state management tools: Context API, Zustand, Jotai, and TanStack Query for server state, with patterns and a decision framework.
GuideComplete Guide to React 19 Features
A practical walkthrough of React 19: server components, the use() hook, actions, ref as a prop, document metadata, asset loading, and the React Compiler.
PatternCustom Hook Composition in React
How to compose reusable logic with custom React hooks. Covers hook composition, dependency arrays, context integration, memoization, and testing.
RecipeVirtualize Long Lists with react-window
How to render large lists efficiently in React with react-window 2, covering the List and Grid components, dynamic row heights, and infinite scrolling.
RecipeForm Validation with react-hook-form and Zod
Build type-safe forms in React using react-hook-form with Zod schema validation, including nested fields, async rules, dynamic fields, and UI library integration.