Lesson 20 — Code Splitting & Lazy Loading (Improving Load Time)

🧭 Introduction

Performance is not only about fast interactions — it’s also about fast loading.

Many React apps suffer from:
❌ Large bundle sizes
❌ Slow first load
❌ Blank screens on slow networks

Why?

Because the entire application JavaScript is loaded at once.

This lesson teaches you how professional React apps load only what is needed, using code splitting and lazy loading.


🎯 What You’ll Learn in This Lesson

By the end of this lesson, you will understand:

  • What bundle size is and why it matters
  • What code splitting means
  • How React lazy loading works
  • How to split routes and components
  • Best practices for lazy loading
  • Common mistakes to avoid

🧠 What Is a Bundle?

When you run:

npm run build

React creates:

  • One or more JavaScript bundles
  • Bundles contain your entire app code

If your app grows:

  • Bundle size increases
  • Load time increases
  • Performance suffers

❌ Problem with Single Large Bundle

Loading everything at once causes:

  • Longer Time To Interactive (TTI)
  • Slower first paint
  • Poor user experience on mobile

👉 Users should not download code they don’t need yet.


🧩 What Is Code Splitting?

Code splitting means:

Breaking your JavaScript bundle into smaller chunks and loading them on demand.

Benefits:

  • Faster initial load
  • Smaller JS files
  • Better performance

⚛️ React.lazy — Lazy Loading Components

React provides built-in lazy loading using React.lazy.


✅ Basic Example

import React, { Suspense } from "react";

const Dashboard = React.lazy(() => import("./Dashboard"));

function App() {
  return (
    <Suspense fallback={<p>Loading...</p>}>
      <Dashboard />
    </Suspense>
  );
}

Dashboard is loaded only when needed
✔ Initial bundle stays small


🧠 Why Suspense Is Required

Lazy-loaded components load asynchronously.

Suspense:

  • Shows fallback UI
  • Prevents app from crashing
  • Improves UX

🧭 Route-Based Code Splitting (Most Important)

This is the most common and powerful use case.


Example — Lazy Routes

const Home = React.lazy(() => import("./pages/Home"));
const Profile = React.lazy(() => import("./pages/Profile"));

function AppRoutes() {
  return (
    <Suspense fallback={<p>Loading page...</p>}>
      <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/profile" element={<Profile />} />
      </Routes>
    </Suspense>
  );
}

👉 Each route loads only when visited.


🧠 Why Route-Based Splitting Is Ideal

Users:

  • Rarely visit all routes
  • Should not download unused pages

This approach:

  • Reduces initial load
  • Scales well
  • Is production standard

📦 Dynamic Imports (Behind the Scenes)

import("./Dashboard");

This creates a separate chunk.

Bundlers like:

  • Vite
  • Webpack

Handle chunking automatically.


🚨 Common Lazy Loading Mistakes

❌ Lazy Loading Everything

Small components don’t need it.


❌ Forgetting Suspense

Causes runtime errors.


❌ Bad Fallback UI

Always show meaningful loading indicators.


❌ Lazy Loading Critical UI

Header, navbar, layout should load immediately.


🧠 What Should Be Lazy Loaded?

✅ Good Candidates

  • Routes
  • Large components
  • Charts
  • Admin panels
  • Rarely used modals

❌ Bad Candidates

  • Buttons
  • Forms
  • Layout components
  • Frequently used UI

⚡ Combining Code Splitting with Performance Tools

Best results when combined with:

  • React Profiler
  • Memoization
  • Virtualization

Performance is holistic, not one technique.


🏗️ Real-World Strategy (Professional)

1️⃣ Identify large routes/components
2️⃣ Lazy load non-critical paths
3️⃣ Keep core UI eagerly loaded
4️⃣ Measure load time improvements
5️⃣ Iterate

This is how production teams optimize load time.


🎯 Best Practices (Senior-Level)

✅ Prefer route-based code splitting
✅ Use meaningful fallback UI
✅ Avoid over-splitting
✅ Measure bundle size regularly
✅ Optimize for real users


❓ FAQs — Code Splitting & Lazy Loading

🔹 Does lazy loading always improve performance?

Mostly yes, but misuse can hurt UX.


🔹 Is React.lazy supported everywhere?

Yes — in modern React apps.


🔹 Should I lazy load Redux store?

No — store should load immediately.


🔹 Is this important for interviews?

Yes — very common senior-level topic.


🧠 Quick Recap

✔ Large bundles slow apps
✔ Code splitting breaks bundles
✔ React.lazy loads components on demand
✔ Route-based splitting is best
✔ Avoid lazy loading critical UI


🎉 Conclusion

Fast apps don’t load everything upfront
they load only what the user needs.

Once you apply code splitting correctly:

  • Load time improves
  • UX feels instant
  • Apps scale smoothly

This lesson completes Section 5 — Performance Optimization, one of the most important skills in advanced React ⚛️⚡


👉 Next Section

SECTION 6 — Advanced React Design Patterns

👉 Next Lesson

Lesson 21 — Container vs Presentational Components

Leave a Comment