Memo vs useMemo in React
Understanding the difference between memo and useMemo helps optimize React apps and improve performance! Here’s the breakdown:
✨ 1. memo: Optimize React components
• Purpose: Prevent unnecessary re-renders of functional components.
• Use Case: Wrapping components that re-render even when props haven’t changed.
• Example:
🛒 Imagine a shopping cart component that re-renders when unrelated states update.
import React from 'react';
const ProductList = React.memo(({ products }) => {
console.log('Rendering ProductList');
return products.map(product => <div key={product.id}>{product.name}</div>);
});
✅ Key: Use memo to wrap components so they only render if props change.
✨ 2. useMemo: Optimize calculations inside components
• Purpose: Memorize expensive calculations to avoid recomputation on every render.
• Use Case: Caching derived data like filtered or sorted lists.
• Example:
🍎 Sorting a list of fruits only when the list changes.
import React, { useMemo } from 'react';
function FruitList({ fruits }) {
const sortedFruits = useMemo(() => {
console.log('Sorting fruits');
return [...fruits].sort();
}, [fruits]);
return sortedFruits.map(fruit => <div key={fruit}>{fruit}</div>);
}
✅ Key: Use useMemo to avoid re-running expensive operations during renders.
🛠️ Both are tools to optimize performance, but use them wisely—premature optimization can backfire!