Skip to content

Lazy Loading and Code Splitting

Reducing bundle size with React.lazy, Suspense, and dynamic imports.

What you'll learn

  • What code splitting is and why it matters
  • Using React.lazy to lazily load components
  • Wrapping lazy components in Suspense with fallbacks
  • Route-based code splitting strategies

Concept

Why Code Splitting?

By default, all your JavaScript is bundled into a single file. As your app grows, this bundle becomes large, slowing the initial page load — the browser must download and parse the entire bundle before anything renders. Code splitting breaks the bundle into smaller chunks that are loaded on demand. This dramatically improves initial load time because the user only downloads the code for the page they are viewing, not the entire application.

React.lazy

React.lazy lets you render a dynamic import as a regular component. You pass it a function that returns import(): const Settings = React.lazy(() => import("./Settings")). The component is loaded only when it is first rendered. The dynamic import() returns a promise that resolves to the module, and React.lazy handles the suspense of waiting for it. This is the simplest way to code-split at the component level.

Suspense

React.lazy components must be wrapped in a <Suspense> boundary, which shows a fallback (like a loading spinner) while the lazy component is loading. You can have multiple Suspense boundaries at different levels — each shows its own fallback independently. Suspense can also be used with data fetching (in experimental concurrent features) and with React Router's lazy route loading. The fallback can be anything: a spinner, a skeleton, or a placeholder layout.

Route-Based Splitting

The most impactful code splitting is route-based: each route's components are in a separate chunk. When the user navigates to a new page, only that page's code is loaded. This is natural with React Router — wrap each route element in a Suspense boundary and use React.lazy for the page components. The initial load only includes the code for the landing page, and other pages load on demand as the user navigates.

Analyzing Bundle Size

Use tools like vite-bundle-visualizer or webpack-bundle-analyzer to see what is in your bundle and identify large dependencies that could be split or replaced. Look for large libraries that are only used on one page — these are prime candidates for lazy loading. Also check for duplicate dependencies and tree-shaking issues where libraries prevent dead code elimination.

Example

              import React, { Suspense, lazy } from "react";
import { BrowserRouter, Routes, Route } from "react-router-dom";

// Lazy-load page components — each becomes a separate bundle chunk.
const Home = lazy(() => import("./pages/Home"));
const Dashboard = lazy(() => import("./pages/Dashboard"));
const Settings = lazy(() => import("./pages/Settings"));

function LoadingFallback() {
  return (
    <div className="loading-screen">
      <div className="spinner" />
      <p>Loading page...</p>
    </div>
  );
}

function App() {
  return (
    <BrowserRouter>
      {/* Suspense shows fallback while any lazy route is loading */}
      <Suspense fallback={<LoadingFallback />}>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/dashboard" element={<Dashboard />} />
          <Route path="/settings" element={<Settings />} />
        </Routes>
      </Suspense>
    </BrowserRouter>
  );
}
            

Each page is lazy-loaded into its own bundle chunk. Suspense shows a loading screen while the chunk downloads. The initial load only includes the Home page code.

Try it

  • Code Minifier

    See how code splitting reduces the size of individual bundle chunks.

  • Code Diff

    Compare bundle structure before and after adding lazy loading.

Common mistakes

The mistake

Using React.lazy without a Suspense boundary

The fix

Every React.lazy component must be inside a Suspense boundary. Without it, React has no fallback to show while loading and will throw an error. Wrap at the route level or component level.

The mistake

Lazy-loading components that are needed on the initial page

The fix

Only lazy-load components that are not needed immediately (other routes, modals, heavy widgets). Lazy-loading the initial page's components adds a loading flash with no benefit.

Practice Lazy Loading and Code Splitting

4 exercises

Practice Lazy Loading and Code Splitting

Look up unfamiliar terms

A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.

View glossary

Build real projects

Apply what you learned by building guided projects with starter code and solutions.

View projects

Decode error messages

Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.

View errors