Your dashboard takes 1.5 seconds to show. Yet 180 KB of its 300 KB of code is just a chart component, which is only used after a button is clicked.
Without any setup, all of an app's JavaScript is sent as one big file (a bundle), and the page only shows once that file has downloaded. Two React tools can change this:
lazysplits one component into its own file (a chunk). That chunk only downloads when the component first renders.Suspenseshows a temporary UI (a fallback) while the chunk is still downloading.
It's like a small food stall. The rice and main dishes are ready in the display case, so customers are served right away. The shaved-ice dessert is only made when someone orders it, and while it's being made the seller says "just a moment". Once the dessert ingredients are out of the fridge, the next order is ready right away. In React, what's in the display case is the first bundle, and the dessert is a component loaded with lazy. "Just a moment" is the fallback, and the ingredients already out of the fridge are a chunk that has already downloaded.
One big bundle, or split
Say your dashboard app is 300 KB, and 180 KB of that is the HeavyChart component, which is only used after a button is clicked.
| Approach | Downloaded before the page shows | Downloaded later |
|---|---|---|
| One bundle | 300 KB | nothing |
HeavyChart made lazy |
120 KB | 180 KB, when the chart first renders |
On a connection of about 200 KB per second, 300 KB takes roughly 1.5 seconds, while 120 KB takes only 0.6 seconds. Users who never open the chart never download those 180 KB at all. Splitting a bundle like this is called code splitting.
lazy and Suspense
Here is HeavyChart loaded with lazy. It only shows after the Load Component button is clicked:
import { lazy, Suspense, useState } from "react"
const HeavyChart = lazy(() => import("./HeavyChart"))
function App() {
const [show, setShow] = useState(false)
return (
<div>
<button onClick={() => setShow(true)}>Load Component</button>
{show && (
<Suspense fallback={<p id="fallback">Loading...</p>}>
<HeavyChart />
</Suspense>
)}
</div>
)
}
import("./HeavyChart")is a dynamic import: an import that runs while the code runs, not at the top of the file. When called,import(...)starts downloading that file and returns a promise right away, which finishes once the file has downloaded. A build tool such as Vite turns that file into a separate chunk automatically.lazy(() => import(...))makes a component that only calls that import when it first renders. The fileHeavyChart.jsxmust have anexport default.lazyis called outside the component, once, just like a normalimport.<Suspense fallback={...}>wraps the lazy component. While its chunk is still downloading, the fallback shows. OneSuspensemay wrap several lazy components at once.fallbackcan be any element: text such as<div id="loading">Loading...</div>, a spinner, or a grey skeleton the size of the content so the page doesn't jump.
Say HeavyChart shows the text Component Loaded! and a chart. This is the order:
| Time | What happens | What shows |
|---|---|---|
| 0 seconds | The button is clicked, HeavyChart renders, the chunk starts downloading |
Loading... |
| 0.9 seconds | The 180 KB chunk is done | Component Loaded! and the chart |
The second time it shows right away
lazy remembers the result of its import. Once the chunk has finished downloading the first time, a HeavyChart that is hidden and then shown again appears right away, with no fallback and no new download. The browser also keeps the chunk file in its cache, so the next visit is faster too.
Simulating it with state
The exercise editor has no other files to import. In the first exercise, the import is imitated with a promise that finishes 300 ms later with { default: Chart }, so a real lazy and Suspense show the fallback. In the second exercise, you imitate three states with ordinary state: not loaded, loading, loaded.
function App() {
const [loaded, setLoaded] = useState(false)
const [loading, setLoading] = useState(false)
const handleLoad = () => {
setLoading(true)
setLoaded(true)
setLoading(false)
}
return (
<div>
<button id="load" onClick={handleLoad}>Load Component</button>
{!loaded && !loading && <p id="placeholder">Click the button to load</p>}
{loading && <p id="fallback">Loading...</p>}
{loaded && <div id="lazy-content">Component Loaded!</div>}
</div>
)
}
- Before the click,
loadedandloadingare bothfalse, so only#placeholdershows. - React groups the three setters in
handleLoadinto one re-render (batching). By the time that render happens,loadingisfalseagain, so#fallbacknever gets a chance to show here. What really shows a fallback while waiting isSuspensewithlazy. - After the click,
#lazy-contentshows and#placeholderis gone.
⚠️ Lazy loading that keeps showing the fallback, or makes things slower
lazyinside a component.const Chart = lazy(...)insideAppmakes a new component on every render: the fallback shows again and the state inside is lost. Writelazyoutside the component.- A named export.
lazyneeds anexport default. If the file usesexport function Chart(a named export: an export with a name, notexport default), writelazy(() => import("./Chart").then((m) => ({ default: m.Chart })))(mholds everything the file exports). - Making every component lazy. Each chunk is one more request. Lazy fits parts that are big and rarely opened: other pages, modals, editors, charts. Parts that are visible at the top of the page right away shouldn't be lazy.
- A placeholder that stays. In the exercises, after the button is clicked, the "Click the button to load" prompt has to disappear, not stay next to the content.
TL;DR: Without any setup, all of an app's JavaScript is sent as one big file (a bundle). lazy(() => import("./HeavyChart")) splits a component into its own file (a chunk) that downloads when that component first renders. <Suspense fallback={...}> shows the fallback (a temporary UI) while the chunk is still downloading. The result is a smaller first bundle and a page that shows sooner: if a 180 KB chart is split from a 300 KB app, only 120 KB downloads at the start. lazy is written outside the component and needs an export default. Once loaded, the component shows right away with no fallback. In the first exercise, the import is imitated with a promise, and in the second, three states (placeholder, #fallback, #lazy-content) are imitated with state.
⚡ One big bundle, or split
Guess first: your app is 300 KB, and 180 KB of it is a chart component only used after a button is clicked. If the chart is split into its own file that only downloads when the chart is needed, how much downloads before the page shows?
Only 120 KB. The 180 KB only downloads when the chart first renders, and a user who never opens it never downloads it.
Meaning: Without any setup, all of an app's JavaScript is sent as one big file (a bundle). Splitting the bundle so that rarely used parts download later is called code splitting. The first bundle is smaller, so the page shows sooner.
⚡ lazy and Suspense
Write:
import { lazy, Suspense, useState } from "react"
const HeavyChart = lazy(() => import("./HeavyChart"))
function App() {
const [show, setShow] = useState(false)
return (
<div>
<button onClick={() => setShow(true)}>Load Component</button>
{show && (
<Suspense fallback={<p id="fallback">Loading...</p>}>
<HeavyChart />
</Suspense>
)}
</div>
)
}
Meaning: lazy(() => import("./HeavyChart")) splits HeavyChart into its own file (a chunk). That chunk only downloads when HeavyChart first renders, here after the Load Component button is clicked. While the chunk is still downloading, Suspense shows the fallback, which is the temporary UI Loading....
⚡ Instant the second time
Meaning: lazy remembers what it imported. Once the chunk has finished downloading the first time, a HeavyChart that's hidden and shown again appears right away, with no fallback and no new download.