tezvyn:

useMemo and useCallback for stable references

AI-drafted, machine-checkedSource: interviewintermediate
WHAT IT TESTS

Memoization hooks.

OUTLINE

useMemo caches a computed value, useCallback caches a function identity across renders; both prevent recompute and unnecessary re-renders of memoized children.

WHAT THIS TESTS Whether you understand referential stability in React and can identify the specific situation where useCallback prevents wasted re-renders, without cargo-culting memoization everywhere.

A GOOD ANSWER COVERS useMemo caches the return value of a function, recomputing it only when one of its dependencies changes, so you avoid repeating an expensive calculation on every render. useCallback caches a function definition itself, returning the same function reference between renders unless its dependencies change; it is effectively useMemo for a function. They matter because in JavaScript a function or object created inline during render is a new reference each time, which can defeat React.memo on child components and retrigger effects whose dependency arrays include that reference. You should stress they have a cost, the dependency comparison and memory, so you use them where re-renders are actually expensive, not on every value. Note they do not persist across unmounts; the cache lives with the component instance.

COMMON WRONG ANSWERS Wrapping every value and function in them by default, adding overhead. Confusing the two, useMemo returns a value, useCallback returns a function. Omitting or misstating dependencies, causing stale closures or constant invalidation. Thinking they cache across unmounts or app sessions. Believing useCallback alone speeds up a child that is not wrapped in React.memo.

LIKELY FOLLOW-UPS Why is useCallback useless without React.memo on the child, how do dependency arrays work, what is referential equality, when does useMemo not help, and how does this interact with FlatList renderItem.

ONE CONCRETE EXAMPLE A parent renders a FlatList whose memoized ListItem receives an onPress handler. If the parent defines onPress inline, every parent re-render, say from an unrelated state change, creates a new function reference, so React.memo sees a changed prop and re-renders every visible ListItem, causing scroll jank. Wrapping onPress in useCallback with a stable dependency list keeps its reference identical across renders, so the memoized items skip re-rendering and the list stays smooth.

Read the original → react.dev

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.