CodePark/ questions / Performance: re-renders & memo
START PRACTICINGPRACTICE
Frontend question · React › Performance: re-renders & memo

What is the difference between useMemo and useCallback, and when are they actually worth using?

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.

  • useMemo caches a computed value. useCallback caches a function.
  • useCallback(fn, d) is the same as useMemo(() => fn, d).
  • Use them for slow calculations.
  • Use them for props passed to memo components and for hook dependencies.
  • Measure first. The React Compiler can add memoization automatically.