React Memoization Techniques
React re-renders components by default whenever their parent renders, which can cause performance issues in large apps. Memoization helps optimize performance by preventing unnecessary renders of components or recalculations of expensive functions.
Using React.memo()
React.memo()
is a higher-order component that prevents functional components from re-rendering unless their props change.
import React from 'react';
const ExpensiveComponent = React.memo(function ExpensiveComponent({ value }) {
console.log('Rendering ExpensiveComponent');
return <div>Value: {value}</div>;
});
Wrap only components that are pure and benefit from reduced re-rendering.
Using useMemo
and useCallback
useMemo
useMemo
memoizes the result of a computation, avoiding recalculation unless dependencies change.
import { useMemo } from 'react';
function Fibonacci({ n }) {
const fib = useMemo(() => {
function calculateFib(n) {
if (n <= 1) return n;
return calculateFib(n - 1) + calculateFib(n - 2);
}
return calculateFib(n);
}, [n]);
return <p>Fibonacci of {n} is {fib}</p>;
}
useCallback
useCallback
memoizes a function reference, which helps when passing callbacks to memoized components to avoid triggering re-renders.
import { useCallback, useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const increment = useCallback(() => {
setCount(c => c + 1);
}, []);
return <button onClick={increment}>Count: {count}</button>;
}
Code Splitting and Lazy Loading
Code splitting reduces the initial bundle size by loading parts of your app only when needed. React supports this via React.lazy
and Suspense
.
Using React.lazy
import React, { Suspense } from 'react';
const LazyComponent = React.lazy(() => import('./LazyComponent'));
function App() {
return (
<div>
<Suspense fallback={<p>Loading...</p>}>
<LazyComponent />
</Suspense>
</div>
);
}
This will load LazyComponent
only when it is rendered, improving the loading time of the initial app.
Best Practices for Code Splitting
- Split large components or pages using
React.lazy
- Group related components together with dynamic imports
- Use route-based code splitting with libraries like React Router + lazy loading
Conclusion
Performance optimization is crucial for delivering fast, responsive user experiences. Memoization, lazy loading, and smart rendering strategies ensure your React apps scale efficiently. In the next post, we’ll explore how to test React components and applications using tools like Jest and React Testing Library.
0 Comments