useMemo vs useCallback?
Practice this questionWANT TO UNDERSTAND THE CONCEPT FIRST?Learn useMemo vs useCallback?
Definition:
useMemo caches a calculated value between renders until its dependencies change. useCallback preserves a function reference under the same dependency idea. They can reduce repeated work or unstable props, but memoization is an optimization rather than a correctness guarantee.
Key points:
-
useMemocaches a calculated value;useCallbackcaches a function reference. -
They can help with expensive calculations or stable props for memoized children.
-
They add complexity and do not stop every re-render; measure first.
-
A memoized callback can still capture stale values if required dependencies are missing.
Comparison:
| Point | useMemo | useCallback |
|---|---|---|
| Preserves | Calculated value | Function reference |
| Typical use | Expensive filtering | Callback passed to a memoized child |
| Dependencies change | Recalculate the value | Use a new function reference |
| Guarantees no re-renders | No | No |
Example — inside a component:
const visible = useMemo(
() => items.filter(item => item.active),
[items]
);
const select = useCallback(id => onSelect(id), [onSelect]);- Import these hooks from React. Use them only when the avoided work or stable identity is useful.
Interview point:
- Explain the downstream work avoided—an expensive calculation or a memoized child's render—not just that a value is cached.
Adapted from 06_REACT_NEXTJS.md · “useMemo vs useCallback?”. Code examples are study fragments. Difficulty and core labels are editorial estimates; version-specific behavior should be checked against your project.