By the end of this lesson, you will:
Code Splitting is a technique that allows you to split your JavaScript bundle into smaller chunks, so your app loads faster by only loading what’s needed at the moment.
👎 Without Code Splitting:
👍 With Code Splitting:
import() – The FoundationModern JavaScript allows you to import modules dynamically like this:
import('path/to/Component').then((module) => {
const MyComponent = module.default;
});
✅ Loads a module only when needed
✅ Webpack creates a separate chunk for this module
React simplifies code splitting with:
React.lazy()const MyComponent = React.lazy(() => import('./MyComponent'));
SuspenseSuspenseWrap lazy-loaded components in a fallback loader:
import React, { Suspense, lazy } from 'react';
const Dashboard = lazy(() => import('./Dashboard'));
function App() {
return (
<Suspense fallback={<p>Loading...</p>}>
<Dashboard />
</Suspense>
);
}
🪄 While Dashboard is loading, the user sees “Loading…”
const Home = lazy(() => import('./pages/Home'));
const About = lazy(() => import('./pages/About'));
function AppRoutes() {
return (
<Suspense fallback={<div>Loading page...</div>}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
</Routes>
</Suspense>
);
}
✅ Loads each page only when needed
✅ Great for large multi-page apps
HeavyChart.js with a slow-loading chart.React.lazy() to load it on button click.<Suspense fallback={<Loading />}>.const HeavyChart = lazy(() => import('./HeavyChart'));
function Analytics() {
const [showChart, setShowChart] = React.useState(false);
return (
<div>
<button onClick={() => setShowChart(true)}>Load Chart</button>
{showChart && (
<Suspense fallback={<div>Loading chart...</div>}>
<HeavyChart />
</Suspense>
)}
</div>
);
}
✅ Lazy-load routes or large feature components
✅ Use meaningful fallbacks (spinners, skeletons, etc.)
✅ Combine with React Router for route-level splitting
✅ Group components logically if they load together often
❌ Don’t lazy-load small or frequently used components
❌ Always wrap lazy components in Suspense
❌ React.lazy() only supports default exports
Workaround for named exports:
const Special = lazy(() =>
import('./SpecialComponent').then((mod) => ({ default: mod.NamedExport }))
);
| Feature | Purpose |
|---|---|
React.lazy() |
Load components on demand |
Suspense |
Show fallback while component loads |
import() |
Dynamically fetch JS modules |
| Code Splitting | Improve performance by reducing bundle size |
Suspense improve the user experience?Build a Responsive Portfolio Page that:
React.lazy() and SuspenseRefactor one of your apps to:
SuspenseLet me know if you’d like the next lesson to be on:
✅ Reusable Component Patterns
✅ Form Handling and Validation
✅ React Performance Optimization
Not a member yet? Register now
Are you a member? Login now