Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

React useMemo vs useCallback: Memoization, React.memo, and When to Skip

Three tools for three different problems: a cached value, a stable function identity, a skipped subtree. How to tell which one the render cost needs.

~4 min readReact
#React#Performance#Hooks
3D illustration of memoized dependency cache gates preserving referential equality down a component tree

Quick Summary

useMemo caches the result of a computation between renders. useCallback caches a function identity. They are the same hook with different shapes: useCallback(fn, deps) is useMemo(() => fn, deps). React.memo is a different tool — it skips re-rendering a component when its props are shallow-equal to the previous render.

These are performance tools, and they have a cost: every memoized value is a dependency array to maintain, an extra comparison per render, and a place where a stale closure can hide. The default in modern React should be not memoizing, then adding memoization where a profiler shows a real problem.

Three specific cases justify it. An expensive pure computation on every render. A function identity that is a dependency of another hook or a prop of a memoized child. A component subtree that re-renders on every parent render while its props do not change. Everything else is ceremony — and since React 19's compiler can insert memoization automatically, hand-written useMemo is increasingly about correctness of identity rather than raw speed.

Basic Syntax & Signature

tsx
import { memo, useCallback, useMemo, useState } from "react"; type Row = { id: number; name: string; score: number }; // memo: skip re-render when props are shallow-equal. const RowView = memo(function RowView({ row, onSelect }: { row: Row; onSelect: (id: number) => void; }) { return <li onClick={() => onSelect(row.id)}>{row.name}: {row.score}</li>; }); export function Table({ rows }: { rows: Row[] }) { const [query, setQuery] = useState(""); const [selected, setSelected] = useState<number | null>(null); // useMemo: skip an expensive derivation when inputs are unchanged. const visible = useMemo(() => { const q = query.toLowerCase(); return rows.filter((r) => r.name.toLowerCase().includes(q)); }, [rows, query]); // useMemo for a derived aggregate. const total = useMemo( () => visible.reduce((sum, r) => sum + r.score, 0), [visible], ); // useCallback: stable identity for a prop of a memoized child. const handleSelect = useCallback((id: number) => setSelected(id), []); return ( <div> <input value={query} onChange={(e) => setQuery(e.target.value)} /> <p>{total} across {visible.length} rows, selected {selected ?? "none"}</p> <ul> {visible.map((row) => ( <RowView key={row.id} row={row} onSelect={handleSelect} /> ))} </ul> </div> ); }

Signatures:

ts
function useMemo<T>(factory: () => T, deps: readonly unknown[]): T; function useCallback<T extends Function>(callback: T, deps: readonly unknown[]): T; function memo<P extends object>( Component: (props: P) => ReactNode, arePropsEqual?: (prev: P, next: P) => boolean, ): React.NamedExoticComponent<P>;

Key Comparison Table

ToolMemoizesCompared withSkips
useMemoA computed valueObject.is on each depRecomputing on every render
useCallbackA function referenceObject.is on each depNew identity on every render
React.memoA component's rendered outputShallow compare of propsRe-rendering the component
memo + comparatorThe same, with custom rulesYour arePropsEqualRe-rendering on deep-equal props
useReducerState transitions, not renders—Nothing by itself
SymptomWrong toolRight tool
Child re-renders on every parent renderuseMemo on its dataReact.memo on the child + stable props
Expensive sort on every keystrokeReact.memouseMemo on the sorted list
Effect re-subscribes every renderuseMemouseCallback for the handler, or a ref
Object prop causes change detectionReact.memo aloneuseMemo for the object
Slow render of a long listMore useMemouseDeferredValue, virtualization
Stale value inside a memoized callbackuseCallback with []Include the dep, or use an updater

Practical Edge Cases & Deep Dives

1. memo defeated by an inline prop

tsx
import type { CSSProperties, ReactNode } from "react"; const Item = memo(function Item({ label, style }: { label: string; style: CSSProperties; }) { console.log("render", label); return <li style={style}>{label}</li>; }); function Broken({ items }: { items: string[] }) { return ( <ul> {items.map((label) => ( // New object every render: memo always sees a changed prop. <Item key={label} label={label} style={{ color: "red" }} /> ))} </ul> ); } const redStyle: CSSProperties = { color: "red" }; function Fixed({ items }: { items: string[] }) { return ( <ul> {items.map((label) => ( <Item key={label} label={label} style={redStyle} /> ))} </ul> ); }

React.memo compares props with Object.is per key, so a fresh object literal defeats it entirely — and the fix in most cases is a module-level constant or a memoized value, not a custom comparator. A custom comparator that deep-compares every prop usually costs more than the render it avoids.

2. The children trick instead of memoizing a subtree

tsx
function ExpensiveChart({ data }: { data: number[] }) { console.log("chart render"); return <svg width={100} height={20}>{data.map((d, i) => ( <rect key={i} x={i * 2} width={1} height={d} /> ))}</svg>; } function Panel({ children }: { children: ReactNode }) { const [open, setOpen] = useState(false); return ( <section> <button onClick={() => setOpen((o) => !o)}>{open ? "hide" : "show"}</button> {open && children} </section> ); } function Dashboard({ data }: { data: number[] }) { // The chart element is created by Dashboard and passed as a prop, so // toggling `open` in Panel does not re-render the chart at all. return <Panel><ExpensiveChart data={data} /></Panel>; }

This is more effective than wrapping ExpensiveChart in memo, because the element object is reused across Panel's renders — no prop comparison is even needed. It is the standard answer to "my component re-renders because its parent's local state changed".

3. useCallback only helps when the identity is observed

tsx
import { useEffect, useState } from "react"; function Search({ onSearch }: { onSearch: (q: string) => void }) { const [q, setQ] = useState(""); // Useless: a plain <button> does not care about identity. const plain = useCallback(() => onSearch(q), [onSearch, q]); // Useful: this effect depends on the function identity. useEffect(() => { const id = setTimeout(() => onSearch(q), 300); return () => clearTimeout(id); }, [q, onSearch]); return ( <form> <input value={q} onChange={(e) => setQ(e.target.value)} /> <button type="button" onClick={plain}>search</button> </form> ); }

If nothing compares the function — no memoized child, no dependency array, no subscription — useCallback changes nothing but allocates a cache entry and adds a place to forget a dependency. The meaningful case here is the effect, which would restart its timer on every render if onSearch were an inline arrow.

4. A memo whose dependency is an object from props

tsx
type Filters = { min: number; max: number }; function Results({ filters }: { filters: Filters }) { // `filters` may be a new object each parent render even if it is equal. // Destructure to primitives so the dependency is stable by value. const { min, max } = filters; const rows = useMemo(() => expensive(min, max), [min, max]); return <p>{rows.length}</p>; } function expensive(min: number, max: number) { return Array.from({ length: 1000 }, (_, i) => i).filter((n) => n >= min && n <= max); }

Destructuring dependencies to primitives is the cheapest fix for identity churn. When the dependency genuinely is a structure, memoize it where it is created (useMemo in the parent) rather than memoizing every consumer downstream.

5. When useMemo is the wrong tool for correctness

tsx
function Config() { // Wrong: relying on useMemo for a side effect. React may discard the cache. const loaded = useMemo(() => { localStorage.setItem("seen", "1"); return localStorage.getItem("seen"); }, []); // Right: a side effect belongs in an effect. useEffect(() => { localStorage.setItem("seen", "1"); }, []); // Right: a one-time expensive initialization belongs in lazy state. const [index] = useState(() => buildIndex()); return <p>{loaded} {index.length}</p>; } function buildIndex(): number[] { return Array.from({ length: 100 }, (_, i) => i); }

The React documentation is explicit that useMemo is a performance optimization, not a semantic guarantee: React may throw away cached values, for example to free memory. Code that breaks when the compute function runs twice is code that used useMemo as a lifecycle hook.

6. useDeferredValue as an alternative to heavy memoization

tsx
function LiveFilter({ items }: { items: string[] }) { const [query, setQuery] = useState(""); const deferredQuery = useDeferredValue(query); // The input updates immediately; the expensive list lags one render behind. // The filter still runs per keystroke, but at a lower priority. const visible = items.filter((item) => item.toLowerCase().includes(deferredQuery.toLowerCase()), ); const isStale = query !== deferredQuery; return ( <div style={{ opacity: isStale ? 0.6 : 1 }}> <input value={query} onChange={(e) => setQuery(e.target.value)} /> <ul>{visible.map((v) => <li key={v}>{v}</li>)}</ul> </div> ); }

useDeferredValue keeps the typing responsive without caching anything: the urgent update renders first, the list renders again at lower priority. For a list of a few thousand items this is usually a better trade than memoizing every step, and it composes with React.memo rather than replacing it.

Common Compilation/Runtime Mistakes

SymptomCauseFix
Memoized child still re-rendersInline object, array, or function propStable references, or memo with a comparator
useMemo recomputes every renderDep is recreated each renderDestructure to primitives, or memoize the dep
Stale value inside useCallbackMissing dependencyAdd the dep, or use the functional updater
Memoized value never updatesDep array [] but inputs changeInclude the inputs
memo does not stop context-driven rendersContext changedMemo does not affect context subscriptions
Component keeps state after switching dataSame component position and keyGive it a new key
useMemo used for a side effectWrong hookuseEffect, or lazy useState
Lint: "React Hook useMemo has a missing dependency"Dep omitted deliberatelyRestructure, or the value does not belong in a memo
Performance worse after adding memoComparison cost exceeds the renderRemove it; profile first
useCallback on every handlerReflexive memoizationKeep plain functions; memoize only observed identities

The practical rule: memoize data for a computation you can measure, memoize functions for identities something compares, and memoize components for subtrees that re-render without changing. Everything else should be a plain function and a plain value — the fastest code is the code React does not need to compare.

Try matching browser tools

All tools

Small utilities that fit React work — they run entirely in this browser tab, so nothing you paste leaves your device.

All React guides

More in React

All React guides

The guides filed next to this one in React, in library order.