useMemo, useCallback and useRef
Harry
· 28 Sep 2026
· 1 views
Log in to track your progress and mark lessons complete.
useMemo: Expensive Derivations
const total = useMemo(
() => books.reduce((s, b) => s + b.price, 0),
[books]
)Recalculates only when books changes. Do not memoise cheap work - the comparison itself costs.
useCallback: Stable Function Identity
const addBook = useCallback(
(b) => setBooks(xs => [...xs, b]),
[]
)Pass to memoized children so they skip re-renders. Pair with React.memo on the child.
useRef: Values Without Re-renders
const inputRef = useRef(null)
const focus = () => inputRef.current?.focus()
const renders = useRef(0); renders.current++Refs hold timers, DOM nodes and counters that must not trigger renders.
When NOT to Optimize
Measure first. Premature memo everywhere makes code harder to read for zero gain - React is already fast for normal trees.
- useMemo caches values, useCallback caches functions, useRef caches without rendering.
- Optimize measured hotspots, not everything.