Back to blog
Optimizing React Performance: A Practical Guide
·2 min read
reactperformanceweb-developmentjavascript
Optimizing React Performance: A Practical Guide
Performance issues in React apps often come from unnecessary re-renders. Here are practical techniques I've used in production.
Profiling First
Always measure before optimizing:
import { Profiler } from "react";
function onRender(id: string, phase: string, actualDuration: number) {
console.log(`${id} ${phase}: ${actualDuration}ms`);
}
<Profiler id="ExpensiveList" onRender={onRender}>
<ExpensiveList items={items} />
</Profiler>;
Technique 1: Memoization
Use React.memo for components that receive the same props frequently:
const ExpensiveItem = React.memo(function ExpensiveItem({
data,
}: {
data: Item;
}) {
return <div>{/* expensive render */}</div>;
});
Technique 2: Virtual Scrolling
For long lists, render only what's visible:
// Using a virtualized list approach
function VirtualizedList({ items, itemHeight, windowHeight }) {
const [scrollTop, setScrollTop] = useState(0);
const startIndex = Math.floor(scrollTop / itemHeight);
const endIndex = Math.min(
startIndex + Math.ceil(windowHeight / itemHeight) + 1,
items.length
);
const visibleItems = items.slice(startIndex, endIndex);
// render only visible items
}
Technique 3: Code Splitting
Split your bundle to load only what's needed:
const HeavyComponent = dynamic(() => import("./HeavyComponent"), {
loading: () => <Skeleton />,
});
Results
After applying these techniques to a dashboard at work:
- Initial load time: 3.2s → 1.1s
- Interaction latency: 200ms → 50ms
- Bundle size: 450KB → 180KB
Key Takeaways
- Always profile before optimizing
- Focus on the biggest bottlenecks
- Memoization is not always the answer
- Code splitting has the highest impact for initial load
Share this post
More posts
Building a Modern Portfolio with Next.js and Tailwind CSS
A step-by-step guide to creating a professional portfolio website using Next.js 14, TypeScript, and Tailwind CSS.
Transfer Learning for Low-Resource Languages: Lessons Learned
Insights and practical tips from my research on applying transfer learning techniques to Nepali and other low-resource languages.