Optimizing React Performance With Memoization and Code Splitting
As your React application grows, so does the importance of performance optimization. In this article, we’ll explore two powerful strategies—memoization and code splitting—to make your apps faster and more efficient.
Why Performance Matters
Modern web apps can be complex and component-heavy. Without optimization, unnecessary re-renders and large bundle sizes can slow down your UI and negatively affect user experience. Let's fix that.
1. Using React.memo
to Avoid Unnecessary Re-Renders
React.memo
is a higher-order component that prevents re-renders if props haven't changed.
const ExpensiveComponent = React.memo(({ data }) => {
console.log("Rendering ExpensiveComponent");
return {data};
});
By wrapping your component with React.memo
, you save resources by avoiding unnecessary recalculations.
2. Memoizing Functions With useCallback
When you pass functions to child components, they often re-render because functions are recreated on every render. useCallback
fixes that:
const handleClick = useCallback(() => {
console.log("Clicked");
}, []);
This ensures the same function reference is used unless dependencies change.
3. Memoizing Values With useMemo
Use useMemo
to cache the result of expensive calculations:
const computedValue = useMemo(() => {
return expensiveFunction(input);
}, [input]);
This is useful for data transformations or filtering that doesn't need to run on every render.
4. Code Splitting With React.lazy
and Suspense
Code splitting breaks your bundle into smaller pieces, loading them on demand. This drastically improves initial load times.
const LazyComponent = React.lazy(() => import('./HeavyComponent'));
function App() {
return (
Loading...