Code Splitting & Lazy Loading

0/2 in this phase0/36 across the roadmap

📖 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:

  1. Route-based splitting: Load each page/route only when visited.
  2. Component-based splitting: Load heavy components (like a Chart or a Code Editor) only when they are about to be displayed.

💻 Code Example

codeTap to expand ⛶
1import React, { lazy, Suspense } from 'react';
2import { BrowserRouter, Routes, Route } from 'react-router-dom';
3
4// 1. Import components lazily
5// These will be in separate .js files in the final build
6const Home = lazy(() => import('./pages/Home'));
7const Dashboard = lazy(() => import('./pages/Dashboard'));
8const HeavyChart = lazy(() => import('./components/HeavyChart'));
9
10function 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>
20
21 {/* 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

  1. Use React.lazy to split your routes in a multi-page app.
  2. Observe the 'Network' tab in Chrome DevTools to see new .js files loading as you navigate.
  3. Use 'Dynamic Imports' for a library like lodash or moment.js only inside the function where it is used.
  4. Analyze your bundle size using a tool like rollup-plugin-visualizer or source-map-explorer.

⚠️ Common Mistakes

  • Not wrapping lazy components 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