Skip to content
ClapelloNotes by Barath
ReactCh 09 · 3/6
Core5 min readUpdated

React / 48

Lazy loading with lazy and Suspense

TL;DR

Split your app into chunks the browser downloads only when needed. lazy() loads a component on first render; Suspense shows a fallback while it arrives.

Bundles and chunks

Before

index.js

shellHomeMenuCartAdminchart library

one big file, downloaded and parsed before anything shows

After code splitting

index.js

shellHome

small: the first screen shows sooner

Menu-[hash].js · Cart-[hash].js

MenuCart

loaded when the user opens them

Admin-[hash].js

Adminchart library

most users never download it

Before: the first visit downloads every page. After: it downloads the shell and the home page; other chunks load the first time they're needed, then come from the cache.

A bundle is the JavaScript file your build produces. Code splitting (also called chunking, dynamic bundling or on-demand loading) breaks it into chunks. All of these names describe the same idea.

The trigger is JavaScript's dynamic import(). A normal import at the top of a file is bundled in. import("./Admin.jsx") written as a function call tells the bundler "make this a separate file, and load it when this line runs". It returns a Promise for the module.

lazy + Suspense

React needs two things to render code that isn't downloaded yet:

  1. lazy()

    Wraps the dynamic import and gives you a component. The first time React tries to render it, it starts the download and suspends (pauses that part of the tree).
  2. Suspense

    A boundary that catches the pause and shows its fallback until the code arrives, then swaps in the real component.
App.jsx
import { lazy, Suspense, useState } from "react";
 
const AdminPanel = lazy(() => import("./AdminPanel.jsx"));
 
export default function App() {
  const [showAdmin, setShowAdmin] = useState(false);
  return (
    <main>
      <h1>Tasty Bites</h1>
      <button onClick={() => setShowAdmin(true)}>Open admin</button>
      {showAdmin && (
        <Suspense fallback={<p>Loading admin…</p>}>
          <AdminPanel />
        </Suspense>
      )}
    </main>
  );
}

AdminPanel.jsx must export default its component. The download happens once: React caches the loaded module, so opening it again is instant.

Load the admin page on demand

Try it
  • network
  • index.jsloaded at start
  • Admin-[hash].jsnot loaded

Admin is closed. Its code hasn't been requested.

The first open downloads the chunk while Suspense shows the fallback. Close and reopen: it's instant, because the chunk is cached.

Split at routes first

The best split points are pages: a user is on one route at a time, so each route's code is a natural chunk.

router.jsx
import { lazy, Suspense } from "react";
import { createBrowserRouter } from "react-router";
import Home from "./pages/Home.jsx";
 
const About = lazy(() => import("./pages/About.jsx"));
 
function AboutPage() {
  return (
    <Suspense fallback={<p>Loading…</p>}>
      <About />
    </Suspense>
  );
}
 
export const router = createBrowserRouter([
  { path: "/", Component: Home },
  { path: "/about", Component: AboutPage },
]);

Home is imported normally, so it ships in the main bundle. About becomes its own chunk.

After that, split heavy, rarely used pieces: a rich-text editor, a charts library, a map. Don't lazy-load small components that appear on the first screen anyway; you'd add a request and a flash of fallback for nothing.

Named exports

lazy expects the module's default export. For a named export, map it to default yourself:

const SalesChart = lazy(() =>
  import("./Charts.jsx").then((module) => ({ default: module.SalesChart }))
);

Pros and cons

ProsCons
Smaller first download: the first screen appears sooner, especially on slow phones and networksA short delay the first time a lazy part opens
Users never download features they don't useMore loading states to design
Better caching: change the admin page, and only its chunk is re-downloadedA chunk can fail to load (bad network, a new deploy), so you need an error boundary
Less JavaScript to parse at startupToo many tiny chunks means many small requests

Don't

lazy() inside a component

function Dashboard() {
  // a new component type every render,
  // so its state resets every time
  const Chart = lazy(() => import("./Chart.jsx"));
  return <Chart />;
}

Do

lazy() at the top of the module

const Chart = lazy(() => import("./Chart.jsx"));
 
function Dashboard() {
  return <Chart />;
}

Gotchas

Recall

Can you answer these?

0/5

Answer out loud (or in your head) before you tap. That's what makes it stick.

Saved on this device only. No login.