These three are performance optimization tools.
They help avoid unnecessary re-renders and expensive recalculations.
Let’s break each one clearly.
✅ 1. useMemo — Cache Expensive Calculations
📌 Use useMemo when:
- You have expensive calculations (loops, filtering, sorting)
- You want to avoid recalculating on every render
- You depend on a specific state/prop to compute something
Example:
const sortedData = useMemo(() => {
return data.sort((a, b) => a.value - b.value); // expensive
}, [data]);
✔ Only recalculates when data changes
✔ Prevents slow re-renders
🔥 Best for:
- Big loops
- Heavy computations
- Filtered lists
- Derived data
✅ 2. useCallback — Cache Functions (avoid re-creating)
📌 Use useCallback when:
- You pass a function to a child component
- That child is wrapped in
React.memo - You want to prevent the child from re-rendering unnecessarily
Example:
const handleClick = useCallback(() => {
console.log("Clicked");
}, []);
✔ Same function instance on every render
✔ Prevents React from thinking: “Function changed → re-render child”
🔥 Best for:
- Event handlers passed to children
- Preventing unnecessary renders in memoized components
✅ 3. React.memo — Prevent Component Re-rendering
📌 Use React.memo when:
- Component re-renders but props do not change
- You want to skip re-render unless props change
Example:
const Child = React.memo(function Child({ value }) {
return <div>{value}</div>;
});
✔ React will not re-render this unless value changes
🔥 Best for:
- Pure UI components
- List items
- Buttons / small reusable components
🎯 How They Work Together (Most Important)
In real projects, you use all three together:
Example:
const Parent = () => {
const [count, setCount] = useState(0);
const heavyValue = useMemo(() => expensiveCalculation(count), [count]);
const handleClick = useCallback(() => {
setCount(c => c + 1);
}, []);
return <Child onClick={handleClick} value={heavyValue} />;
};
const Child = React.memo(({ onClick, value }) => {
return <button onClick={onClick}>{value}</button>;
});
Here:
- useMemo → avoids recalculating heavy value
- useCallback → avoids creating new function every render
- React.memo → avoids re-rendering the child unnecessarily
⚠ When NOT to Use These
Do not use them for everything.
Avoid when:
- Component is small
- No expensive calculations
- No deep prop changes
- No child memoization
Overusing them can hurt performance.
🎯 Short Interview Answer
useMemo: Cache expensive calculations (e.g., sorting, filtering).
useCallback: Cache functions to avoid re-renders, especially when passing functions to memoized children.
React.memo: Prevent component from re-rendering if props didn't change.
Together, they help avoid unnecessary renders and improve performance in React apps.