useMemo & useCallback: Performance

Medium•

Premature memoization can add complexity with negligible benefit. Strong engineers optimize measured bottlenecks and reason about cache invalidation boundaries.

Quick Decision Guide

useMemo caches values; useCallback caches function identity.

Use when: - expensive computations dominate render cost - child memoization depends on stable props

Interview signal: tie memoization to a concrete cost model, not habit.

Cost Model First

🔥 Insight

Optimization starts with identifying dominant cost, not by sprinkling hooks.

🧠 Mental Model

without memo: compute on every render
with memo: compare deps + compute only on invalidation

Memoization has overhead (dependency comparison, cache storage, cognitive load).

When It Helps vs Hurts

const filtered = useMemo(() => heavyFilter(items, query), [items, query])
const onSelect = useCallback((id) => select(id), [select])

Helps

•Expensive derived computations
•Stable callback identity for memoized children

Hurts

•Cheap computations wrapped everywhere
•Incorrect dependencies causing stale values

Rules of Hooks (and why)

•Call hooks at the top level of React components or custom hooks.
•Do not call hooks inside conditions, loops, or nested functions.
•Only call hooks from React function components or other custom hooks.

These rules follow from React's render model:

•React relies on consistent hook call order across renders.
•Hook identity is tied to position in the render sequence.
•Conditional or reordered hook calls can misassociate state/effects and produce incorrect behavior.

Trade-offs and Interview Takeaway

Trade-offs

•Better runtime only when protecting meaningful work
•Higher maintenance cost from dependency correctness requirements

🎯 Interview Takeaway

State the bottleneck, show why memoization targets it, and mention invalidation/dependency risk.

Key Takeaways

1Memoization is a trade-off, not a default best practice.
2Tie useMemo/useCallback to real bottlenecks.
3Dependency correctness affects both performance and behavior.
4Cost model explanations stand out in interviews.