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.
npm install and npm run dev. Press Show stats.
lazy
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:
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
const StatsPanel = lazy(() => wait(800).then(() => import("./StatsPanel.jsx")));Rules
- Declare
lazycomponents 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.)
Load on hover
Start downloading the stats code when the pointer moves over Show stats, so it's usually ready by the click.
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
let statsPromise;
const loadStats = () => (statsPromise ??= wait(800).then(() => import("./StatsPanel.jsx")));
const StatsPanel = lazy(loadStats);<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.
Completion is saved in this browser only. It does not measure mastery.