Memoizing values and functions
Every render recreates the values and functions defined inside a component. useMemo caches the result of a computation and useCallback caches a function reference, both keyed by a dependency array.
- useMemo returns a value, recomputed only when a dependency changes
- useCallback returns the same function, recreated only when a dependency changes
- useCallback fn deps is the same as useMemo that returns fn deps
Why stable references matter
These hooks matter most when the value flows into a memoized child or another hook dependency. A stable reference lets memo skip a render or stops an effect from firing every time.
- Use useMemo for expensive calculations or to stabilize objects
- Use useCallback to keep callback props stable
- An empty dependency array means the value is computed once
When not to bother
Memoizing a cheap value can cost more than recomputing it. Reach for these hooks when there is a real expense or a referential identity requirement.
Hook caching
Key idea
useMemo caches a computed value and useCallback caches a function, both by dependencies, so memoized children and effects see stable references instead of fresh ones each render.