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
useMemo | useCallback | |
|---|---|---|
| Returns | the result of calling compute() | fn itself |
| Typical use | expensive derived data, stable objects/arrays | stable callbacks for memoized children or effect deps |
| Example | useMemo(() => 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";23export function ProductPage({ products }: { products: { id: string; price: number }[] }) {4 const [taxRate, setTaxRate] = useState(0.18);56 // useMemo: caches a VALUE7 const totalWithTax = useMemo(8 () => products.reduce((sum, p) => sum + p.price, 0) * (1 + taxRate),9 [products, taxRate]10 );1112 // useCallback: caches a FUNCTION13 const formatPrice = useCallback(14 (amount: number) => new Intl.NumberFormat("en-IN", { style: "currency", currency: "INR" }).format(amount),15 []16 );1718 // Same as the useCallback above:19 // const formatPrice = useMemo(() => (amount: number) => ..., []);2021 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.