React  

React useMemo vs useCallback: What's the Difference and When to Use Each?

โš–๏ธ What’s the Difference Between useCallback and useMemo in React?

React gives you two powerful hooks to optimize performance: useMemo and useCallback. They both deal with memoization, but serve different purposes.

Let’s clarify the confusion with examples, use cases, and a head-to-head comparison.

๐Ÿ”„ useMemo – Memoize a Value

useMemo returns a memoized value, which is recalculated only when dependencies change.

โœ… Use When

You want to avoid recalculating expensive values (e.g., filtering, calculations, formatting) on every render.

๐Ÿง  Example

const expensiveValue = useMemo(() => {
    return computeHeavyTask(data);
}, [data]);

๐Ÿ“ Use case: Filtering lists, formatting large data, complex math.

๐Ÿ” useCallback – Memoize a Function

useCallback returns a memoized function. It's useful when you're passing functions as props to child components that are optimized with React.memo.

โœ… Use When

You want to prevent function re-creation between renders unless dependencies change.

๐Ÿง  Example

const handleClick = useCallback(() => {
    doSomething();
}, [dependency]);

๐Ÿ“ Use case: Event handlers, callbacks passed to child components.

๐Ÿงช Why Does It Matter?

In React, functions and objects are recreated every time a component re-renders—even if the logic hasn’t changed. This can cause unnecessary renders in child components and performance issues in large apps.

๐Ÿ†š useMemo vs useCallback – Comparison Table

Feature useMemo useCallback
Returns A memoized value A memoized function
Use case Expensive computations Function identity preservation
Helps with Avoiding unnecessary recalculations Avoiding unnecessary re-renders
Common with Computed props React.memo child components
Syntax useMemo(() => value, [deps]) useCallback(() => fn, [deps])

๐Ÿšซ Don’t Overuse Them

  • Use these only when needed (i.e., you’ve profiled and noticed performance issues).
  • Adding too many useMemo or useCallback calls can make your code harder to read without meaningful performance gains.

โœ… Conclusion

  • ๐Ÿง  Use **useMemo** when you want to memoize a value (e.g. result of a computation).
  • ๐Ÿ”ง Use **useCallback** when you want to memoize a function (e.g. event handler).

๐Ÿ’ก A good rule: If you’re passing a function as a prop to a child component wrapped in React.memo, use useCallback.