useCallback
useMemo
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 returns a memoized value, which is recalculated only when dependencies change.
You want to avoid recalculating expensive values (e.g., filtering, calculations, formatting) on every render.
const expensiveValue = useMemo(() => { return computeHeavyTask(data); }, [data]);
๐ Use case: Filtering lists, formatting large data, complex math.
useCallback returns a memoized function. It's useful when you're passing functions as props to child components that are optimized with React.memo.
React.memo
You want to prevent function re-creation between renders unless dependencies change.
const handleClick = useCallback(() => { doSomething(); }, [dependency]);
๐ Use case: Event handlers, callbacks passed to child components.
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(() => value, [deps])
useCallback(() => fn, [deps])
**useMemo**
**useCallback**
๐ก A good rule: If you’re passing a function as a prop to a child component wrapped in React.memo, use useCallback.