useMemo caches the result of a calculation between renders. useCallback caches the function itself, so you get the same function reference between renders.
useMemo(() => compute(a, b), [a, b]) recalculates only when a dependency changes. useCallback(fn, deps) is the same as useMemo(() => fn, deps).
They are worth it in three situations:
- The calculation is noticeably slow, for example filtering thousands of items.
- The value or function is passed to a component wrapped in
memo. A new reference each render would defeat the memoization. - The value is a dependency of another hook, such as
useEffect.
Otherwise they add complexity for little gain. Measure with the React DevTools Profiler first. The React Compiler, which is opt-in, can add this memoization automatically.
useMemocaches a computed value.useCallbackcaches a function.useCallback(fn, d)is the same asuseMemo(() => fn, d).- Use them for slow calculations.
- Use them for props passed to
memocomponents and for hook dependencies. - Measure first. The React Compiler can add memoization automatically.