Skip to content
Tutorials Center
My learning

Topics

Lesson 51 of 132 ยท Data and Async

The use Hook and Suspense

Learn React's use hook and Suspense - reading promises and context during render, loading fallbacks, nested boundaries, skeletons, and the promise identity pitfall.

In Fetching Data you loaded data the classic way: render once with nothing, start a request in an effect, store the result in state, and render again. Every component that loads data ends up with the same three-state bookkeeping (loading, error, data), and the user sees a cascade of spinners as each child discovers what it needs.

React 19 offers a second model. A component can simply read a promise while it renders. If the promise has not finished, React pauses that component, shows a fallback chosen by the nearest <Suspense> boundary, and tries again when the promise settles. The hook that does the reading is called use. This lesson explains how it works, how to draw loading states with boundaries, and the one mistake nearly everyone makes at first: creating the promise in the wrong place.

The mental model: a component that can wait

Normal rendering is synchronous. A component runs, returns JSX, and is done. With use(promise), a component may say: "I cannot finish rendering until this value exists." React reacts like this:

  1. It calls your component. Your code reaches use(promise).
  2. The promise is still pending, so React suspends the component. It throws away the half-finished attempt and does not commit it.
  3. It walks up the tree to the nearest <Suspense> and shows that boundary's fallback instead.
  4. When the promise resolves, React renders the component again. This time use returns the resolved value immediately and rendering finishes.
  5. If the promise rejects, use throws the error during render, which the nearest error boundary catches.

So the code you write reads like synchronous code, with no loading flag and no effect:

JSX
function Profile({ userPromise }) {
  const user = use(userPromise); // pauses here until the data exists
  return <h2>{user.name}</h2>;
}

The cost of this convenience is a rule: React must be able to ask "is this the same promise as last time?" The promise has to come from somewhere stable. We will break that rule on purpose in a moment.

Your first Suspense boundary

Our editor has no network, so we simulate a server with setTimeout. The small fetchUser helper below stores each promise in a Map, so asking for the same user twice returns the same promise object. That is the "stable promise" requirement in its simplest form.

use(promise) with a Suspense fallback

Watch the preview and the console. First you see the heading and "Loading profile..." The console starts with Profile: calling use() but no "got" line, because that first attempt was abandoned at use. About 150 ms later the promise resolves and React renders Profile again. In our run the console showed Profile: calling use() three times and a single Profile: got Ada Lovelace at the end. The exact number of attempts is an internal detail (development builds retry more eagerly), so never rely on it. What you can rely on is the rule: a component that suspends may run its body several times, and only the last, complete run is committed.

Two details matter:

  • Code before use runs on both attempts, so keep it free of side effects (it should be pure anyway, see Pure Components).
  • fetchUser(1) is called inside App, which also renders more than once in real apps. It is safe here only because the Map hands back the same promise each time.

use is not like other hooks in one respect: you may call it inside if statements and loops, after an early return, as long as it is called while a component or hook is rendering. That is why it can read context conditionally, as the next section shows.

The promise identity pitfall

What if you create the promise inside the component that reads it?

JSX
function Profile() {
  const user = use(fetchUser(1)); // a brand-new promise on every render
  // ...
}

Each render attempt creates a new pending promise. React suspends on it, then when it resolves and React renders again, Profile runs again and creates yet another new pending promise. The loop never ends. Run the broken version and see what happens.

A promise created during render (fails on purpose)

Run it and wait: the preview shows Loading... and stays there. In our run there was no error and no text in the console, even after more than a second, although the promise resolved after 100 ms. The component keeps suspending on a fresh pending promise each time, so it never completes. The silence is the nasty part: nothing tells you what is wrong, you just see a spinner that never ends. If you ever meet an endless fallback, look for a promise created during render. (Some React setups also log a warning about an uncached promise; do not count on it.)

There are three standard cures:

  1. Create the promise above the component that suspends, in a parent that does not suspend itself (often an event handler or a route loader), and pass it down as a prop.
  2. Cache it by a key, as fetchUser does with its Map. Same key, same promise.
  3. Use a framework or library whose data layer already does this. React Router loaders, Next.js Server Components, and libraries such as TanStack Query's suspense mode all return stable promises or throw them in a way React understands.

In practice you rarely write the cache yourself; the lesson on caching and server state builds a small one so you can see the idea.

Do not keep a promise in useState or useMemo and call that a cache. A suspended component that is rendering for the first time has no state yet; React discards it, so the stored promise is discarded with it. The cache must live outside the component: module scope, a parent that is already mounted, or a library.

Reading context with use

use also accepts a context object. use(ThemeContext) returns the same value as useContext(ThemeContext), with the extra freedom that it can be called conditionally.

use(context) after an early return

useContext would have to run before the early return, so the decorative badge would subscribe to the theme for nothing. With use the hook call sits where the value is needed. For the full story on context see Context.

Nested boundaries and loading order

A Suspense boundary does not wrap one component; it wraps a region of the page. All suspended components below it share its fallback. Several boundaries nested inside each other let you reveal the page in layers instead of showing one big spinner.

Nested Suspense boundaries

The outer boundary waits for Title (fast); only then does the page appear, and the inner boundaries show their own fallbacks until Summary and Chart are ready. The shape of your boundaries is a design choice:

  • One boundary at the top: the page appears all at once. Simple, but slow content holds everything back.
  • A boundary per section: each part pops in when ready. Users see something sooner, but too many independent spinners look jumpy.
  • A boundary around only what is slow, with fast, critical content outside it, is usually the sweet spot.

Remember that when a component inside a boundary suspends, the whole boundary's children swap to the fallback, including siblings that were ready. Place the boundary tightly around the slow part if you want its siblings to stay visible.

Skeletons instead of spinners

A plain "Loading..." line causes layout shift when content arrives. A skeleton is a grey placeholder with the same size as the real content, so the page does not jump. Because the fallback is just JSX, a skeleton is just a component.

A skeleton fallback

Errors: what happens on rejection

If the promise rejects, use throws that reason while rendering. Without an error boundary the whole root unmounts and the user is left with a blank page. Always pair Suspense (the "not yet" state) with an error boundary (the "failed" state) around any data you read this way. The next lesson, Error Boundaries, shows how.

Streaming, in one paragraph

On the server, Suspense gains a second power. With server rendering frameworks, React can send the page shell immediately with fallbacks in place, then stream each section's HTML as its data arrives and swap it in without a full reload. Your boundaries decide the seams. You cannot try this in our editor (no server), but the code you write is identical, which is one reason the model is worth learning.

TEXT
Browser receives:  <header>...</header>  <div>[fallback: Loading summary...]</div>
...later, same connection:  <template>real summary HTML</template> + tiny swap script

When to use it, and when not

Use use(promise) and Suspense when a framework or library provides stable promises, or when you create the promise in an event handler or route loader and pass it down. Prefer it for data that gates a region of the page.

Avoid inventing your own promise caching for production. Avoid it when you need rich behavior such as retries, background refetching, or invalidation; that is what server-state libraries are for. And avoid wrapping everything in one giant boundary, which makes a single slow request freeze the whole screen.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does React do when a component calls use(promise) and the promise is still pending?

    React abandons that render attempt, shows the fallback of the closest Suspense boundary, and renders the component again once the promise settles.
  2. 2. Why is use(fetchUser(1)) with a fetchUser that always creates a new promise a bug?

    The promise must be stable between renders. Cache it by key outside the component or pass it from a parent that does not suspend.
  3. 3. Which statement about use is true?

    Unlike other hooks, use may be called conditionally, but it must still be called while rendering, not in event handlers or effects.
  4. 4. A page has one Suspense boundary at the top and three slow sections inside it. What does the user see until all three are ready?

    A suspended component swaps the entire nearest boundary to its fallback. Add inner boundaries if you want sections to appear independently.
  5. 5. What happens when the promise passed to use rejects and no error boundary exists above?

    A rejected promise throws during render. Without an error boundary the whole tree unmounts, so pair Suspense with an error boundary.

Summary

  • use(promise) reads a promise during render; a pending promise suspends the component and the nearest <Suspense fallback> is shown.
  • A suspended component is rendered again when the promise settles, so code before use must be pure.
  • The promise must be stable between renders: cache it by key outside the component or create it in a parent or event handler. Creating it inline in the suspending component fails.
  • use(Context) works like useContext but may be called conditionally.
  • Nested boundaries reveal a page in layers; place each boundary around the slow part, and use skeletons to avoid layout shift.
  • Rejections are thrown during render, so combine Suspense with an error boundary.

Next: Error Boundaries