Fullstack CourseLearn by building
Back to week 2

Topic

Caching functions with useCallback

Definition

useCallback is a React Hook that caches a function definition between re-renders and returns the same function reference until its listed dependencies change.

In simpler words

useCallback(fn, deps) is like useMemo(() => fn, deps) for functions — keep the same function identity when children or Effects care about it.

Stable callbacks, memoized children, Effect dependencies, and avoiding needless wrapping.

After this you can

  • Stabilize handlers passed to memoized children or listed in Effect dependencies.
  • Explain the trade-off to a teammate using a small example.
  • Name at least one common bug pattern for this topic.

Understand Caching functions with useCallback

Stable callbacks, memoized children, Effect dependencies, and avoiding needless wrapping.

Start by identifying which value or browser behavior changes. Then describe the UI from that current input instead of editing the DOM as a separate source of truth.

Caching functions with useCallback in code

const onSelect = useCallback((id: string) => {
  setSelectedId(id);
}, []);

useEffect(() => {
  document.title = selectedId ?? "Tickets";
}, [selectedId]);

Read the example from data and control flow to the resulting UI. Keep the component boundary small.

Apply Caching functions with useCallback

Keep rendering as a calculation. Put user-triggered changes in event handlers, preserve UI memory in state, and reserve external synchronization for Effects or the server-state layer.

Name values by their UI meaning, test the loading and error path when data is remote, and avoid keeping two editable copies of the same value.

Ask before adding code: is this local UI memory, shared client state, or Nest-owned server state?

Where bugs hide

Definition

High-bug areas are places where a small API misuse looks correct but produces stale UI, duplicate work, or silent failures.

In simpler words

Each mistake below shows Wrong vs Right code — compare them side by side.

When something misbehaves, match the symptom to a pattern below before rewriting the feature.

Prefer fixing the ownership or update path over adding another Effect or sync step.

Mistake: wrap every handler in useCallback

// Wrong
const onClick = useCallback(() => setOpen(true), []);
<button onClick={onClick}>Open</button>

// Right
<button onClick={() => setOpen(true)}>Open</button>

Most event handlers do not need a stable identity. Add useCallback when a child or Effect depends on reference equality.

Mistake: Empty deps while closing over changing state

// Wrong
const save = useCallback(() => {
  api.create(draft);
}, []); // draft stale

// Right
const save = useCallback(() => {
  api.create(draft);
}, [draft]);
// or read draft from a ref / submit handler that already has the latest value

Stale closures are the same class of bug as Effect dependency mistakes.

Mistake: useCallback instead of fixing an Effect design

// Wrong
const load = useCallback(() => list(status), [status]);
useEffect(() => { load(); }, [load]);

// Right
useEffect(() => { list(status); }, [status]);
// better for Nest lists: useQuery({ queryKey: ["t", status], queryFn: list })

Prefer fewer Effects and Query keys over stacking memo wrappers around fetch helpers.

Live playground

Caching functions with useCallback sandbox

Change one input at a time and predict the next render.

Effects depend on the handler. A new function each render re-fires the Effect; useCallback keeps identity until deps change.

status=open · renders=1 · Effect with plain fn runs=0 · Effect with useCallback runs=0

const onChange = useCallback(() => { ... }, [status]);
useEffect(() => { /* subscribe */ }, [onChange]);

Keep in mind

  • Keep the formal definition in mind; it explains which tool belongs where.
  • Prefer one source of truth over synchronized copies of the same value.
  • When behavior surprises you, trace: input → update → render → committed UI.
  • Study the Wrong vs Right examples in “Where bugs hide” before you merge.

Test

Check your understanding

At least 10 questions — mix of concept, syntax, practical, and logic. Score ≥ 80% (enforced by the API) to save progress.

Checking your session…

12 questions · concept 3 · syntax 3 · practical 3 · logic 3

Concept1. What does useCallback cache?
Concept2. When is useCallback most useful?
Syntax3. Which is a correct useCallback call?
Syntax4. How do you express useCallback with useMemo?
Practical5. An Effect lists `onMessage` as a dependency, and `onMessage` is recreated every render. Symptom?
Practical6. Best default for a local button handler?
Logic7. useCallback(() => api.create(draft), []) while draft changes each keystroke. What is wrong?
Logic8. Why is wrapping a fetch helper in useCallback + useEffect often the wrong fix for Nest lists?
Concept9. Does useCallback cache the HTTP response of the function it wraps?
Syntax10. Which deps keep `useCallback((id) => select(id, filter), ...)` honest?
Practical11. A memoized TicketRow receives onSelect. Parent recreates onSelect every render. Result?
Logic12. What should you try before adding useCallback?