โ๏ธ 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
.