React / 48
Lazy loading with lazy and Suspense
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
one big file, downloaded and parsed before anything shows
After code splitting
index.js
small: the first screen shows sooner
Menu-[hash].js · Cart-[hash].js
loaded when the user opens them
Admin-[hash].js
most users never download it
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:
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).Suspense
A boundary that catches the pause and shows itsfallbackuntil the code arrives, then swaps in the real component.
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.
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.
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
| Pros | Cons |
|---|---|
| Smaller first download: the first screen appears sooner, especially on slow phones and networks | A short delay the first time a lazy part opens |
| Users never download features they don't use | More loading states to design |
| Better caching: change the admin page, and only its chunk is re-downloaded | A chunk can fail to load (bad network, a new deploy), so you need an error boundary |
| Less JavaScript to parse at startup | Too 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.
