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.

Hooks cheat sheet for memo callback and ref

Key Points

  • useMemo caches values, useCallback caches functions, useRef caches without rendering.
  • Optimize measured hotspots, not everything.
Share this post:

Comments (0)

Please login or register to comment.

Create a free account to keep reading

You've enjoyed a free tutorial! Register (it's free) to unlock every tutorial, track your progress and save code.

or sign in with your account

Already have an account? Log in