Skip to content

Loading Code on Demand

The Course
•
15 min study

Data isn't the only thing that can arrive later. In an app without code splitting, the initial bundle includes components the user may never open. A panel that few people open, especially one that brings a large library with it, slows everyone down. lazy loads a component's code the first time it renders.

Stats, loaded when asked for React · 7 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); // A pretend server. It logs each request, answers after a delay, and can't // load topic 4, so you can see what happens when a request fails. const topics = [ { id: 1, title: "Suspense", summary: "Show a fallback while part of the page waits for data." }, { id: 2, title: "use", summary: "Read a promise during render, and suspend until it's ready." }, { id: 3, title: "Transitions", summary: "Keep showing the old screen while the new one loads." }, { id: 4, title: "Broken topic", summary: "" }, ]; const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); export async function fetchTopicList() { console.log("request: topic list"); await wait(400); return topics.map(({ id, title }) => ({ id, title })); } export async function fetchTopic(id) { console.log(`request: topic ${id}`); await wait(id === 3 ? 1200 : 500); if (id === 4) throw new Error("Topic 4 couldn't be loaded."); return topics.find((topic) => topic.id === id); } import { lazy, Suspense, useState } from "react"; import ErrorBoundary from "./ErrorBoundary.jsx"; // The lab loads files instantly, so wait a little to show what a real // download of a separate chunk feels like. const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const StatsPanel = lazy(() => wait(800).then(() => import("./StatsPanel.jsx"))); export default function App() { const [showStats, setShowStats] = useState(false); return ( <main> <h1>Study Hub</h1> <button onClick={() => setShowStats(true)} disabled={showStats}>Show stats</button> {showStats && ( <ErrorBoundary fallback={(error) => <p className="error">Stats couldn't load: {error.message}</p>}> <Suspense fallback={<p className="muted">Loading stats…</p>}> <StatsPanel /> </Suspense> </ErrorBoundary> )} </main> ); } import { fetchTopic, fetchTopicList } from "./api.js"; // One promise per request, reused on every render. use() needs this: a new // promise each render would mean a new request each render. const cache = new Map(); function cached(key, load) { if (!cache.has(key)) cache.set(key, load()); return cache.get(key); } export const getTopicList = () => cached("topics", fetchTopicList); export const getTopic = (id) => cached(`topic:${id}`, () => fetchTopic(id)); export function invalidate(key) { cache.delete(key); } import { Component } from "react"; // Catches rendering errors below it and shows fallback(error, reset). // When resetKey changes, it clears the error without remounting its children, // so a Suspense boundary inside it keeps its content during a transition. export default class ErrorBoundary extends Component { state = { error: null }; static getDerivedStateFromError(error) { return { error }; } componentDidUpdate(previous) { if (this.state.error && previous.resetKey !== this.props.resetKey) this.reset(); } reset = () => this.setState({ error: null }); render() { if (this.state.error) return this.props.fallback(this.state.error, this.reset); return this.props.children; } } // Imagine this pulls in a large charting library: worth loading only when asked for. export default function StatsPanel() { return ( <section className="panel"> <h2>Stats</h2> <p>4-day streak · 210 minutes this week</p> </section> ); } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; } [role="tablist"] { display: flex; gap: 0.25rem; border-bottom: 1px solid #d6dde6; margin-bottom: 0.75rem; } [role="tab"] { border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; padding: 0.4rem 0.8rem; } [role="tab"][aria-selected="true"] { border-bottom-color: #087ea4; color: #06617f; font-weight: 600; } .stars button { border: 0; background: none; padding: 0 0.1rem; font-size: 1.3rem; color: #b9c2cd; } .stars button[aria-checked="true"], .stars button.on { color: #d99a00; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.

Press Show stats.

lazy

JavaScript
const StatsPanel = lazy(() => import("./StatsPanel.jsx"));

import() with brackets is a dynamic import: it loads a module when it's called, and returns a promise. lazy wraps it in a component. The first time <StatsPanel /> renders, it starts the import and suspends, so the nearest <Suspense> shows its fallback. After that, it renders like any component.

On your own computer, Vite puts StatsPanel.jsx and everything only it imports into a separate file, downloaded only when needed. The lab has every file already, so App.jsx adds an 800 ms wait to show what the download feels like:

JavaScript
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const StatsPanel = lazy(() => wait(800).then(() => import("./StatsPanel.jsx")));

Rules

  • Declare lazy components at the top level of a module, never inside a component. Inside, each render would make a new component type, losing its state and loading again.
  • The module needs a default export, which becomes the component.
  • Pair it with an error boundary. A chunk can fail to download, on a bad connection or after a new version is deployed.

Predict: a failed download

The lab can't lose a download, so pretend: replace import("./StatsPanel.jsx") with Promise.reject(new Error("Failed to fetch dynamically imported module")), the error a browser gives for a chunk that didn't arrive. Press Show stats.

What you'll see

Loading stats…, then Stats couldn't load: Failed to fetch dynamically imported module. The rejected import throws, and the error boundary around the Suspense catches it. Without the boundary, the whole app would disappear.

(Importing a file that doesn't exist, such as ./Stats.jsx, fails differently in the lab: it can't even compile, because the lab checks every import before running. On your own computer, Vite reports it when building.)

Exercise

Load on hover

Start downloading the stats code when the pointer moves over Show stats, so it's usually ready by the click.

Your working space React · 7 files
import { createRoot } from "react-dom/client"; import App from "./App.jsx"; import "./styles.css"; createRoot(document.getElementById("root")).render(<App />); // A pretend server. It logs each request, answers after a delay, and can't // load topic 4, so you can see what happens when a request fails. const topics = [ { id: 1, title: "Suspense", summary: "Show a fallback while part of the page waits for data." }, { id: 2, title: "use", summary: "Read a promise during render, and suspend until it's ready." }, { id: 3, title: "Transitions", summary: "Keep showing the old screen while the new one loads." }, { id: 4, title: "Broken topic", summary: "" }, ]; const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); export async function fetchTopicList() { console.log("request: topic list"); await wait(400); return topics.map(({ id, title }) => ({ id, title })); } export async function fetchTopic(id) { console.log(`request: topic ${id}`); await wait(id === 3 ? 1200 : 500); if (id === 4) throw new Error("Topic 4 couldn't be loaded."); return topics.find((topic) => topic.id === id); } import { lazy, Suspense, useState } from "react"; import ErrorBoundary from "./ErrorBoundary.jsx"; // The lab loads files instantly, so wait a little to show what a real // download of a separate chunk feels like. const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); const StatsPanel = lazy(() => wait(800).then(() => import("./StatsPanel.jsx"))); export default function App() { const [showStats, setShowStats] = useState(false); return ( <main> <h1>Study Hub</h1> <button onClick={() => setShowStats(true)} disabled={showStats}>Show stats</button> {showStats && ( <ErrorBoundary fallback={(error) => <p className="error">Stats couldn't load: {error.message}</p>}> <Suspense fallback={<p className="muted">Loading stats…</p>}> <StatsPanel /> </Suspense> </ErrorBoundary> )} </main> ); } import { fetchTopic, fetchTopicList } from "./api.js"; // One promise per request, reused on every render. use() needs this: a new // promise each render would mean a new request each render. const cache = new Map(); function cached(key, load) { if (!cache.has(key)) cache.set(key, load()); return cache.get(key); } export const getTopicList = () => cached("topics", fetchTopicList); export const getTopic = (id) => cached(`topic:${id}`, () => fetchTopic(id)); export function invalidate(key) { cache.delete(key); } import { Component } from "react"; // Catches rendering errors below it and shows fallback(error, reset). // When resetKey changes, it clears the error without remounting its children, // so a Suspense boundary inside it keeps its content during a transition. export default class ErrorBoundary extends Component { state = { error: null }; static getDerivedStateFromError(error) { return { error }; } componentDidUpdate(previous) { if (this.state.error && previous.resetKey !== this.props.resetKey) this.reset(); } reset = () => this.setState({ error: null }); render() { if (this.state.error) return this.props.fallback(this.state.error, this.reset); return this.props.children; } } // Imagine this pulls in a large charting library: worth loading only when asked for. export default function StatsPanel() { return ( <section className="panel"> <h2>Stats</h2> <p>4-day streak · 210 minutes this week</p> </section> ); } body { font: 15px/1.5 system-ui, sans-serif; margin: 0; background: #f4f6f9; color: #1c2430; } main { max-width: 56rem; margin: 1rem auto; padding: 0 1rem; } h1 { margin: 0 0 0.5rem; font-size: 1.4rem; } input, select, button, textarea { font: inherit; } input, select, textarea { padding: 0.3rem 0.5rem; border: 1px solid #c4ccd6; border-radius: 6px; } button { padding: 0.25rem 0.7rem; border: 1px solid #c4ccd6; border-radius: 6px; background: white; cursor: pointer; } .toolbar { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-bottom: 0.75rem; } .board { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 0.75rem; } .column { background: #e9edf2; border-radius: 10px; padding: 0.6rem; min-height: 6rem; } .column h2 { margin: 0 0 0.5rem; font-size: 0.95rem; } .count { color: #5c6878; font-weight: normal; } .cards { list-style: none; margin: 0; padding: 0; display: grid; gap: 0.4rem; } .card { background: white; border: 1px solid #d6dde6; border-radius: 8px; padding: 0.45rem 0.6rem; } .card button.title { border: 0; padding: 0; background: none; text-align: left; font-weight: 600; } .card.selected { outline: 2px solid #087ea4; } .muted { color: #5c6878; font-size: 0.85rem; } .panel { margin-top: 0.75rem; background: white; border: 1px solid #d6dde6; border-radius: 10px; padding: 0.75rem 1rem; } .panel h2 { margin: 0 0 0.25rem; font-size: 1.05rem; } .error { color: #b42318; } [role="tablist"] { display: flex; gap: 0.25rem; border-bottom: 1px solid #d6dde6; margin-bottom: 0.75rem; } [role="tab"] { border: 0; border-bottom: 2px solid transparent; border-radius: 0; background: none; padding: 0.4rem 0.8rem; } [role="tab"][aria-selected="true"] { border-bottom-color: #087ea4; color: #06617f; font-weight: 600; } .stars button { border: 0; background: none; padding: 0 0.1rem; font-size: 1.3rem; color: #b9c2cd; } .stars button[aria-checked="true"], .stars button.on { color: #d99a00; }
Runs with Vite on your computer: unzip, then npm install and npm run dev.
Hint 1: the idea

Two places need the download: the hover handler, to start it early, and lazy, to wait for it. They must share one promise. If each starts its own, the hover download is wasted and the click waits the full time again.

Hint 2: a first step

Name the loader first: move the function you pass to lazy into a constant, loadStats, pass that to lazy, and call it from onMouseEnter too. Hover, wait, then click: it still takes about 0.8 seconds, because each call starts a new download. Change loadStats so later calls return what the first one started.

Show one solution
JavaScript
let statsPromise;
const loadStats = () => (statsPromise ??= wait(800).then(() => import("./StatsPanel.jsx")));
const StatsPanel = lazy(loadStats);
JSX
<button onClick={() => setShowStats(true)} onMouseEnter={loadStats} disabled={showStats}>Show stats</button>

Hover for a second, then click. In our tests, the panel appeared after about 0.3 seconds instead of 0.8. Loading stats… still flashes: lazy suspends the first time it renders, even when the code has already arrived, and React keeps a fallback on screen for about 300 ms once shown, to avoid flicker. Preloading shortens the wait; it doesn't remove the fallback.

Was this article helpful?

Your response is saved on this device.