Code Splitting & Lazy Loading
📖 Concept
As your app grows, your JavaScript bundle becomes huge. A user might only visit the Home page, but they are forced to download the code for the Dashboard, Settings, and Profile pages too.
Code Splitting allows you to break your app into smaller chunks and only load them when they are needed.
React.lazy:
Allows you to define a component that is loaded dynamically. It must be rendered inside a <Suspense> component.
Suspense: A component that allows you to show a "fallback" (like a loading spinner) while its children are being loaded.
Common Patterns:
- Route-based splitting: Load each page/route only when visited.
- Component-based splitting: Load heavy components (like a Chart or a Code Editor) only when they are about to be displayed.
💻 Code Example
1import React, { lazy, Suspense } from 'react';2import { BrowserRouter, Routes, Route } from 'react-router-dom';34// 1. Import components lazily5// These will be in separate .js files in the final build6const Home = lazy(() => import('./pages/Home'));7const Dashboard = lazy(() => import('./pages/Dashboard'));8const HeavyChart = lazy(() => import('./components/HeavyChart'));910function App() {11 return (12 <BrowserRouter>13 {/* 2. Suspense provides a fallback while code is fetching */}14 <Suspense fallback={<div className="p-10 text-center">Loading chunk...</div>}>15 <Routes>16 <Route path="/" element={<Home />} />17 <Route path="/dashboard" element={<Dashboard />} />18 </Routes>19 </Suspense>2021 {/* 3. Splitting a single heavy component */}22 <div className="mt-20">23 <Suspense fallback={<p>Loading Chart...</p>}>24 <HeavyChart />25 </Suspense>26 </div>27 </BrowserRouter>28 );29}
🏋️ Practice Exercise
- Use
React.lazyto split your routes in a multi-page app. - Observe the 'Network' tab in Chrome DevTools to see new
.jsfiles loading as you navigate. - Use 'Dynamic Imports' for a library like
lodashormoment.jsonly inside the function where it is used. - Analyze your bundle size using a tool like
rollup-plugin-visualizerorsource-map-explorer.
⚠️ Common Mistakes
Not wrapping
lazycomponents in<Suspense>(this will cause a crash).Putting
<Suspense>too high up (causing the entire page to disappear while a small component loads).Over-splitting (making hundreds of tiny chunks can slow down the app due to too many network requests).
💼 Interview Questions
🎤 Mock Interview
Practice a live interview for Code Splitting & Lazy Loading