React.memo is a higher-order component that memoizes functional components, preventing unnecessary re-renders when props haven’t changed. It’s React’s built-in optimization tool for performance enhancement.
Syntax: const MemoizedComponent = React.memo(Component);
Key benefits:
Simple example:
const UserCard = React.memo(function UserCard({ name, avatar }) {
return (
<div>
<img src={avatar} alt={name} />
<span>{name}</span>
</div>
);
});
React.memo
is a powerful optimization technique that helps improve React application performance by preventing unnecessary re-renders of components with unchanged props. It’s particularly useful in large applications with complex component trees.
React.memo works by memoizing the result of a component’s render. When the parent component re-renders:
Perfect for list items where individual items rarely change but the parent component re-renders frequently.
Components with complex calculations or heavy rendering logic that benefit from caching.
Components that display static data and rarely receive new props.
Components that receive simple props like strings, numbers, or booleans.
// Simple memoization
const ProductItem = React.memo(function ProductItem({ title, price }) {
return (
<div>
<h3>{title}</h3>
<p>${price}</p>
</div>
);
});
// With custom comparison
const TodoItem = React.memo(
function TodoItem({ todo, onUpdate }) {
return (
<div>
<input
type="checkbox"
checked={todo.completed}
onChange={() => onUpdate(todo.id)}
/>
<span>{todo.text}</span>
</div>
);
},
(prevProps, nextProps) => {
// Custom comparison logic
return (
prevProps.todo.id === nextProps.todo.id &&
prevProps.todo.completed === nextProps.todo.completed &&
prevProps.todo.text === nextProps.todo.text
);
}
);
✅ Best for:
❌ Avoid for:
React.memo is an essential tool for React performance optimization. When used correctly, it can significantly improve application responsiveness by eliminating wasteful re-renders while maintaining code simplicity.
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪