The size of your JavaScript bundle directly impacts your First Contentful Paint (FCP) and Largest Contentful Paint (LCP), which are two critical Core Web Vitals metrics that affect both user experience and SEO rankings.
The problem is that most React apps ship one massive JavaScript bundle containing every component, library and feature. Users on mobile devices download megabytes of code for features they might never use. My rule of thumb is that if a feature isn't visible when the page first loads, it shouldn't
Strategic code splitting approaches:
Route-based splliting
import { lazy, Suspense } from 'react';
//Users download only when they visit
const Home= lazy(() => import('./pages/Home'));
const About= lazy(() => import('./pages/About'));
const Detail= lazy(() => import('./pages/Detaile'));
function App() {
return (
<Suspense fallback={<p>Loading...</p>}>
<Routes>
<Route path="/home" element={<Home/>} />
<Route path="/about" element={<About/>} />
<Route path="/detail" element={<Detail/>} />
</Routes>
</Suspense>
);
}
Conponent-based splitting
// Down load hevy component when you need it.
const Video= lazy(() => import('./Video'));
function MediaSection({ showVideo }) {
return (
<div>
{showVideo && (
<Suspense fallback={<p>Loading...</p>}>
<Video/>
</Suspense>
)}
</div>
);
}
Library splitting
// Only load when needed
const PDF = () => import('react-pdf');
const Excel = () => import('xlsx');
async function handleExport(type) {
if (type === 'pdf') {
const { PDFDownloadLink } = await PDF();
// Use PDFDownloadLink
} else if (type === 'excel') {
const XLSX = await Excel();
// Use XLSX
}
}
✨ Code Splitting: Practical Impact Overview
Here’s a simplified breakdown of how different code splitting strategies affect performance and when to use them:
| Strategy | Bundle Size Reduction | Performance Gain (TTI) | Complexity | When It Works Best |
|---|---|---|---|---|
| Route-based split | ~60–80% | ~40–60% faster | Easy | Applications with multiple pages |
| Component split | ~30–50% | ~20–35% faster | Moderate | Pages with many independent features |
| Library split | ~20–40% | ~15–30% faster | Easy | Projects using large third-party libraries |
| Vendor split | ~15–25% | ~10–20% faster | Easy | Long-term caching optimization |
| Dynamic import | ~40–70% | ~30–50% faster | Moderate | Features loaded on demand |
| Prefetching | N/A (preloading) | ~50–80% faster navigation | Moderate | Predictable user interactions |
Top comments (0)