TExcelTAD
Home › React › React Suspense & lazy

React Suspense & lazy

Some parts of a UI can't render immediately: their code hasn't been downloaded yet, or their data is still loading. <Suspense> lets you declare a loading placeholder for such parts. While anything inside it is "suspended", React shows the fallback; when everything is ready, it swaps in the real content.

jsx
<Suspense fallback={<Spinner />}>
  <SlowPart />
</Suspense>

Two things can suspend a component: a lazy() component whose code is loading, and the use(promise) hook reading a promise that hasn't resolved.

Code splitting with lazy

A big app shouldn't download every screen up front. lazy loads a component's code the first time it is rendered:

jsx
import { lazy, Suspense } from 'react';

const Settings = lazy(() => import('./Settings.jsx'));   // separate file → separate chunk

function App() {
  return (
    <Suspense fallback={<p>Loading settings…</p>}>
      <Settings />
    </Suspense>
  );
}

lazy takes a function returning a promise that resolves to a module with a default export. Bundlers like Vite turn each dynamic import() into a separate file. In the playground we can't import other files, so we simulate a slow download:

jsx · try it yourself
import { lazy, Suspense, useState } from 'react';

function ChartPanel() {
  const bars = [40, 75, 55, 90, 30];
  return (
    <div style={{ display: 'flex', alignItems: 'flex-end', gap: 6, height: 100 }}>
      {bars.map((h, i) => <div key={i} style={{ width: 30, height: h, background: '#61dafb' }} />)}
    </div>
  );
}

// Pretend this module takes 1.5 seconds to download
const LazyChart = lazy(() => new Promise((resolve) => setTimeout(() => resolve({ default: ChartPanel }), 1500)));

export default function App() {
  const [show, setShow] = useState(false);
  return (
    <div>
      <button onClick={() => setShow(!show)}>{show ? 'Hide' : 'Show'} chart</button>
      {show && (
        <Suspense fallback={<p>⏳ Downloading chart code…</p>}>
          <LazyChart />
        </Suspense>
      )}
    </div>
  );
}

Click the button: the fallback appears for 1.5 s, then the chart. Now hide and show it again — once loaded, the code is cached and the chart appears instantly.

Note: Declare lazy components at the top level of a module, never inside another component, or the loading would restart on every render.

Reading data with use

React 19's use hook reads the value of a promise. If the promise is still pending, the component suspends and the nearest <Suspense> shows its fallback:

jsx · try it yourself
import { Suspense, use, useState } from 'react';

function fetchQuote(id) {
  const quotes = [
    'Simplicity is prerequisite for reliability. — Edsger Dijkstra',
    'Make it work, make it right, make it fast. — Kent Beck',
    'Programs must be written for people to read. — Harold Abelson',
  ];
  return new Promise((resolve) => setTimeout(() => resolve(quotes[id % quotes.length]), 1000));
}

function Quote({ promise }) {
  const text = use(promise);       // suspends until the promise resolves
  return <blockquote style={{ fontStyle: 'italic', borderLeft: '4px solid #61dafb', paddingLeft: 10 }}>{text}</blockquote>;
}

export default function App() {
  const [id, setId] = useState(0);
  const [promise, setPromise] = useState(() => fetchQuote(0));

  function next() {
    const nextId = id + 1;
    setId(nextId);
    setPromise(fetchQuote(nextId));   // create the promise in an event, not during render
  }

  return (
    <div>
      <button onClick={next}>Next quote</button>
      <Suspense fallback={<p>Loading quote…</p>}>
        <Quote promise={promise} />
      </Suspense>
    </div>
  );
}

The important rule: the promise must be created outside rendering (in an event handler, a loader, a cache, or a Server Component) and passed in. A promise created inside the component during render would be new on every render and would never settle from React's point of view.

Nested boundaries

You decide how loading states are grouped. One boundary around everything waits for all parts; separate boundaries reveal parts independently:

jsx · try it yourself
import { Suspense, use, useState } from 'react';

const delay = (ms, value) => new Promise((r) => setTimeout(() => r(value), ms));

function Section({ title, promise }) {
  const items = use(promise);
  return (
    <div style={{ border: '1px solid #ddd', padding: 8, borderRadius: 6, marginBottom: 6, width: 260 }}>
      <strong>{title}</strong>
      <ul style={{ margin: 0 }}>{items.map((i) => <li key={i}>{i}</li>)}</ul>
    </div>
  );
}

function makePromises() {
  return {
    profile: delay(500, ['Name: Vy', 'Plan: Pro']),
    posts: delay(1500, ['Hello world', 'Learning Suspense']),
    friends: delay(2500, ['Long', 'Phuong', 'Son']),
  };
}

export default function App() {
  const [p, setP] = useState(makePromises);
  const [grouped, setGrouped] = useState(false);
  const spinner = (label) => <p style={{ color: 'gray' }}>⏳ {label}…</p>;

  const sections = grouped ? (
    <Suspense fallback={spinner('Loading everything')}>
      <Section title="Profile" promise={p.profile} />
      <Section title="Posts" promise={p.posts} />
      <Section title="Friends" promise={p.friends} />
    </Suspense>
  ) : (
    <>
      <Suspense fallback={spinner('Profile')}><Section title="Profile" promise={p.profile} /></Suspense>
      <Suspense fallback={spinner('Posts')}><Section title="Posts" promise={p.posts} /></Suspense>
      <Suspense fallback={spinner('Friends')}><Section title="Friends" promise={p.friends} /></Suspense>
    </>
  );

  return (
    <div>
      <label>
        <input type="checkbox" checked={grouped} onChange={(e) => { setGrouped(e.target.checked); setP(makePromises()); }} /> One boundary for all
      </label>
      {sections}
    </div>
  );
}

Suspense and errors

Suspense handles waiting, not failing. If a lazy import or a promise read with use rejects, the error is thrown to the nearest error boundary. Combine them:

jsx
<ErrorBoundary fallback={<p>Could not load the chart.</p>}>
  <Suspense fallback={<Spinner />}>
    <LazyChart />
  </Suspense>
</ErrorBoundary>

Summary

API Role
<Suspense fallback={…}> shows the fallback while children are suspended
lazy(() => import('./X.jsx')) loads a component's code on first render
use(promise) reads a promise's value; suspends while pending
error boundary handles rejected imports and promises
startTransition keeps already-visible content instead of showing the fallback again (see Transitions)

Tip: Place boundaries where a loading state makes sense to the user: a whole page for route changes, individual panels for dashboards.

Test yourself

What does <Suspense fallback={<Spinner />}> show while a child is loading?

  1. Nothing
  2. The Spinner
  3. The previous page
  4. An error message

What must the function passed to lazy return?

  1. A component
  2. A promise resolving to a module with a default export
  3. A JSX element
  4. A string path

Where should the promise passed to use(promise) be created?

  1. Inside the component during render
  2. Outside rendering, e.g. in an event handler, cache or loader
  3. In a CSS file
  4. Inside the Suspense fallback