useMemo vs useCallback

Core Difference

useMemo() hook memoizes a value (the result of a function call), preventing re-computation unless dependencies change. useCallback() hook memoizes a function, preventing its re-creation unless its dependencies change. Both aim to optimize performance by preserving referential equality.

Key Characteristics

useMemo

  • Memoizes Values: caches the result of an expensive calculation.
  • Returns a Value: the hook returns the memoized value directly.
  • Use Case: optimizing computationally intensive calculations or ensuring stable object/array references for props.

useCallback

  • Memoizes Functions: caches the function definition itself.
  • Returns a Function: the hook returns the memoized function.
  • Use Case: preventing unnecessary re-renders of child components that receive callback functions as props, especially when those children are wrapped in React.memo.

When to Use

useMemo

Use it when you have a complex calculation that produces a value (e.g. filtered list, aggregated data) and you want to avoid re-running that calculation on every render.

useCallback

Use it when you are passing a function down to a child component that is optimized with React.memo. This ensures the child doesn't re-render just because the parent re-created the function on its own render.

Examples

  • Filtering a List (useMemo): memoizing a filtered list of items to avoid re-filtering on every render if the original list or filter criteria haven't changed.
  • Stable Event Handler (useCallback): passing a stable onClick handler to a memoized button component to prevent its re-render.
useMemo vs useCallback · React: Decoded