Suspense & Lazy — React

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…

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:

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>
  )
}

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>
  )
}

⚠️ Lazy loading that keeps showing the fallback, or makes things slower

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.

What you will learn