Performance Optimization Techniques
Learn advanced performance optimization including memo, useMemo, useCallback, and React.memo.
Topics Covered:
Prerequisites:
- Component Composition and Context
Overview
Performance optimization is crucial for large applications. React provides several tools to prevent unnecessary re-renders and expensive recalculations.
React.memo
React.memo is a higher-order component that prevents re-renders when props haven't changed.
const ExpensiveComponent = React.memo(function ExpensiveComponent({ data }) {
// Expensive rendering logic
return <div>{/* Complex UI */}</div>;
});React.memo does a shallow comparison of props. Only re-renders if props actually change.
useMemo for Expensive Calculations
useMemo memoizes the result of expensive calculations, only recomputing when dependencies change.
const expensiveValue = useMemo(() => {
return heavyComputation(items);
}, [items]); // Only recompute when items changeDon't overuse useMemo. Only use it when the calculation is genuinely expensive or when referential equality matters.
Conclusion
Optimize when you have measured a performance problem. Premature optimization can make code more complex without benefits.