⚖️ 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

✅ Conclusion

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