What is the difference between React.memo and useMemo?
Though React.memo
and useMemo
both help optimize performance in React apps by avoiding unnecessary computations or re-renders, they are used in different situations:
Aspect | React.memo | useMemo |
---|---|---|
What it optimizes | Component re-renders | Expensive calculations or derived values |
Usage target | Entire functional components | Inside functional components |
How it works | Memorizes the component output (render) | Memorizes the return value of a function |
Syntax example | React.memo(Component) | const memoizedValue = useMemo(fn, deps) |
Example of React.memo
:
const MyButton = React.memo(function MyButton({ label }) { return <button>{label}</button>; });
The MyButton
component won't re-render if the label
prop doesn't change.
Example of useMemo
:
const sortedItems = useMemo(() => { return items.sort((a, b) => a.value - b.value); }, [items]);
Here, sorting only happens again when items
changes.
Summary:
- Use
React.memo
when you want to optimize entire components. - Use
useMemo
when you want to optimize expensive computations inside components.