Chapter 6: Code Splitting and Lazy Loading
Chapter 6 of 15
Chapter 6: Code Splitting and Lazy Loading
6.1 React.lazy and Suspense
Code splitting allows you to split your bundle into smaller chunks that can be loaded on demand, improving initial load time.
// Lazy load a component
const LazyComponent = React.lazy(() => import('./LazyComponent'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
);
}
// Lazy load with error boundary
function LazyWrapper({ children }) {
return (
<ErrorBoundary>
<Suspense fallback={<LoadingSpinner />}>
{children}
</Suspense>
</ErrorBoundary>
);
}
6.2 Route-Based Code Splitting
import { BrowserRouter, Routes, Route } from 'react-router-dom';
const Home = React.lazy(() => import('./pages/Home'));
const About = React.lazy(() => import('./pages/About'));
const Contact = React.lazy(() => import('./pages/Contact'));
function App() {
return (
<BrowserRouter>
<Suspense fallback={<div>Loading page...</div>}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
</Routes>
</Suspense>
</BrowserRouter>
);
}
6.3 Component-Based Code Splitting
// Split heavy components
const HeavyChart = React.lazy(() => import('./HeavyChart'));
const DataTable = React.lazy(() => import('./DataTable'));
function Dashboard() {
const [showChart, setShowChart] = useState(false);
return (
<div>
<button onClick={() => setShowChart(true)}>Show Chart</button>
{showChart && (
<Suspense fallback={<div>Loading chart...</div>}>
<HeavyChart />
</Suspense>
)}
</div>
);
}
6.4 Preloading Strategies
// Preload on hover
function LinkWithPreload({ to, children }) {
const handleMouseEnter = () => {
const component = React.lazy(() => import(`./pages/${to}`));
// Component is now in cache
};
return (
<Link to={to} onMouseEnter={handleMouseEnter}>
{children}
</Link>
);
}