As React apps grow, you may notice performance starting to lag - sluggish interactions, choppy animations, janky scrolling.
Luckily, there are many great techniques to optimize React app performance. Let’s look at some top tips:
Use React.memo for Component Memoization
The React.memo
API can memoize component outputs:
const MyComponent = React.memo(function MyComponent(props) {
/* only rerenders if props change */
});
This prevents unnecessary re-renders if props stay the same.
Virtualize Long Lists
Rendering thousands of rows kills performance. Virtualize rendering instead:
import { FixedSizeList } from 'react-window';
function List({ data }) {
return (
<FixedSizeList
height={600}
width={300}
itemCount={data.length}
itemSize={35}
>
{({ index, style }) => (
<div style={style}>
{data[index]}
</div>
)}
</FixedSizeList>
);
}
Only items visible on-screen are rendered.
Avoid Reconciliation with Keys
Keys help React distinguish elements from previous renders:
{items.map(item => (
<Item
key={item.id}
item={item}
/>
))}
Mismatching keys lead to full reconciliation.
Split Code with React.lazy
React.lazy
allows code splitting components into separate bundles:
const OtherComponent = React.lazy(() => import('./OtherComponent'));
function MyComponent() {
return (
<React.Suspense fallback={<Loader />}>
<OtherComponent />
</React.Suspense>
);
}
Lazy loading avoids loading unnecessary code until needed.
Use useCallback Hooks
Wrap event handlers in useCallback
to avoid regenerating functions:
const handleClick = useCallback(() => {
// handler logic
}, []);
Avoids re-renders from new event handlers on each call.
Summary
- Memoize components with
React.memo
- Virtualize long lists
- Ensure keys are stable
- Code split with
React.lazy
- Use
useCallback
hook
With some optimization, React can render complex UIs faster than ever.