ReactEasy

Difference: useMemo vs useCallback?

useMemo caches a value returned by a function; useCallback caches the function itself. useCallback(fn, deps) is shorthand for useMemo(() => fn, deps). Both recompute only when dependencies change and both exist to avoid unnecessary work or keep references stable.

Side by side

useMemouseCallback
Returnsthe result of calling compute()fn itself
Typical useexpensive derived data, stable objects/arraysstable callbacks for memoized children or effect deps
ExampleuseMemo(() => items.filter(f), [items, f])useCallback((id) => remove(id), [remove])

Shared rules

  • Dependencies must include every reactive value used.
  • They are performance hints; correct code must not rely on them for behavior.
  • Both are pointless if the consumer does not care about identity or the computation is trivial.

Choosing quickly

  • "I need the result of a computation" → useMemo.
  • "I need to pass a function that should not change every render" → useCallback.

With the React Compiler

Both are applied automatically at build time; in compiled code you rarely write either. Know them for interviews, older codebases and the escape-hatch cases.

Code example

tsx
1import { useCallback, useMemo, useState } from "react";
2
3export function ProductPage({ products }: { products: { id: string; price: number }[] }) {
4 const [taxRate, setTaxRate] = useState(0.18);
5
6 // useMemo: caches a VALUE
7 const totalWithTax = useMemo(
8 () => products.reduce((sum, p) => sum + p.price, 0) * (1 + taxRate),
9 [products, taxRate]
10 );
11
12 // useCallback: caches a FUNCTION
13 const formatPrice = useCallback(
14 (amount: number) => new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR" }).format(amount),
15 []
16 );
17
18 // Same as the useCallback above:
19 // const formatPrice = useMemo(() => (amount: number) => ..., []);
20
21 return (
22 <div>
23 <p>Total: {formatPrice(totalWithTax)}</p>
24 <button onClick={() => setTaxRate((r) => (r === 0.18 ? 0.05 : 0.18))}>Toggle tax</button>
25 </div>
26 );
27}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app