Sub topic 2
Suspense: The Fallback That use Relies On
The use API can read a promise during render, but it has no way to show a loading state by itself. When the promise is still pending, use hands control to Suspense. A Suspense boundary is the component that decides what the user sees while they wait.
This chapter covers how that handoff works, where boundaries go, and how updates behave once content is already on screen. I assume you know function components and props, useState and useContext, and how JavaScript promises and async functions work. You should also know roughly what Suspense is for. Handling rejected promises and keeping promises stable across renders get their own chapters, so here they only get short previews.
What a Suspense boundary does
Suspense is a built-in component with two props that matter here:
children: the tree you want to render.fallback: the React node to show while something insidechildrenis not ready.
A component inside the boundary can say "I can't render yet" and wait. React then replaces the whole boundary's content with the fallback. When the waiting component can render, React swaps the real content back in.
The word for this is suspending. A suspended component has not failed. It has paused until some data arrives.
A boundary covers its entire subtree. If one child suspends, the fallback replaces all of the boundary's content, including siblings that were ready. This is why boundary placement is a design decision. It is covered below.
How use suspends a component
When you call use(promise), React checks what state the promise is in:
- Fulfilled:
usereturns the resolved value immediately, and rendering continues. - Pending: React suspends the component. It stops rendering that component, shows the nearest fallback, and waits for the promise to settle.
- Rejected:
usethrows the rejection reason during render, and the nearest error boundary handles it. See the chapter on rejected promises.
Here is the basic pattern:
import { Suspense, use } from 'react';
function Message({ messagePromise }) {
const message = use(messagePromise);
return <p>Here is the message: {message}</p>;
}
export function MessageContainer({ messagePromise }) {
return (
<Suspense fallback={<p>Waiting for message...</p>}>
<Message messagePromise={messagePromise} />
</Suspense>
);
}Message reads the promise it received as a prop. MessageContainer wraps it in a boundary. The container never checks whether the data is ready. The fallback appears and disappears without any isLoading state in your code.
Compare this with the older approach of useEffect plus useState. There, the component rendered at least once with no data, and you wrote the "no data yet" branch yourself. With use, the component code only describes the success case, and the loading branch lives in the boundary above it.
The sequence of events
The diagram shows what happens on the first render, while the promise is pending.
Two details in this sequence matter in practice.
- React renders
Messageagain from the top. React does not resume the function from the line whereusewas called. It calls the component function again, and this timeusereturns the value. Anything above theusecall runs once per attempt, so the code before it should be pure. Don't put side effects such as logging analytics, mutating variables, or starting requests ahead of ausecall. - The same promise object must come back on the retry. React recognizes the promise it was waiting for by identity. If every attempt creates a new promise, React never finds a settled one. The chapter on keeping promises stable explains this fully.
Where the boundary goes
React looks upward from the suspended component and uses the nearest Suspense ancestor. Where you put the boundary decides which parts of the page show a loading state.
One boundary around everything
import { Suspense, use } from 'react';
function delay(value, ms) {
return new Promise((resolve) => setTimeout(() => resolve(value), ms));
}
const headlinePromise = delay('Release day', 500);
const commentsPromise = delay(['Nice work', 'Shipped!'], 2000);
function Headline() {
const headline = use(headlinePromise);
return <h1>{headline}</h1>;
}
function Comments() {
const comments = use(commentsPromise);
return (
<ul>
{comments.map((comment) => (
<li key={comment}>{comment}</li>
))}
</ul>
);
}
export default function Page() {
return (
<Suspense fallback={<p>Loading page...</p>}>
<Headline />
<Comments />
</Suspense>
);
}The headline is ready after 500 ms and the comments after 2000 ms. With a single boundary, the user sees "Loading page..." for the full two seconds. The headline is ready early, but it stays hidden because the boundary shows its content only when everything inside it can render.
The promises here are created at module level so the example runs as written. Real applications should not start requests at import time. Later chapters show how to create promises safely.
Separate boundaries for independent content
export default function Page() {
return (
<>
<Suspense fallback={<p>Loading headline...</p>}>
<Headline />
</Suspense>
<Suspense fallback={<p>Loading comments...</p>}>
<Comments />
</Suspense>
</>
);
}Now the headline appears after 500 ms while the comments area still shows its own fallback. Each boundary resolves on its own schedule.
Nested boundaries
Boundaries can nest. A suspended component uses the nearest one, so an inner boundary can hold back slow content while an outer boundary covers the page shell:
export default function Page() {
return (
<Suspense fallback={<p>Loading page...</p>}>
<Headline />
<Suspense fallback={<p>Loading comments...</p>}>
<Comments />
</Suspense>
</Suspense>
);
}If Headline suspends, the outer fallback replaces everything, including the nested boundary. If only Comments suspends, the headline stays visible and only the inner fallback shows.
Choosing granularity
| Choice | Effect | Risk |
|---|---|---|
| One boundary high in the tree | Simple. The page appears all at once. | Fast content waits for the slowest content. |
| A boundary around each data-dependent section | Sections appear as they become ready. | Many spinners popping in and layout shifting. |
| Boundaries that match the page layout, such as sidebar, main area, and feed | Loading states match what the user perceives as separate regions. | Needs some design thought. |
A useful rule is to put a boundary where you would be comfortable showing a placeholder to the user. A fallback with the same size and shape as the final content, such as a skeleton block, reduces layout shift.
Boundary placement relative to the suspending component
The boundary must be above the component that calls use. This mistake is common:
function Message({ messagePromise }) {
const message = use(messagePromise);
return (
<Suspense fallback={<p>Waiting...</p>}>
<p>{message}</p>
</Suspense>
);
}This boundary does nothing. use runs in Message, which sits outside the boundary, so the boundary is never reached. The suspension goes to whatever boundary is above Message, or to the root if there is none. Move the boundary to the parent, as in the first example.
Updates after content is already visible
Everything so far describes the first render. Updates behave differently, and this is where many users first see a flicker.
Suppose a page shows a user's profile and a button switches to another user. You store the promise in state and replace it when the user clicks. The new promise is pending, so Profile suspends again. By default React hides the profile that was visible and shows the fallback again. For a fast request, the user sees a brief flash of the loading state.
A transition tells React that an update is not urgent. If a transition would cause already-visible content to be replaced by a fallback, React keeps the old content on screen and prepares the new content in the background. It swaps them when the new content is ready.
import { Suspense, use, useState, useTransition } from 'react';
function fetchUser(id) {
return new Promise((resolve) => {
setTimeout(() => resolve({ id, name: `User ${id}` }), 1000);
});
}
function Profile({ userPromise }) {
const user = use(userPromise);
return <h2>{user.name}</h2>;
}
export default function App() {
const [userPromise, setUserPromise] = useState(() => fetchUser(1));
const [isPending, startTransition] = useTransition();
function showUser(id) {
startTransition(() => {
setUserPromise(fetchUser(id));
});
}
return (
<div style={{ opacity: isPending ? 0.6 : 1 }}>
<button onClick={() => showUser(1)}>User 1</button>
<button onClick={() => showUser(2)}>User 2</button>
<Suspense fallback={<p>Loading profile...</p>}>
<Profile userPromise={userPromise} />
</Suspense>
</div>
);
}Here is what each part does:
- The first render shows "Loading profile..." for one second, then "User 1".
- Clicking "User 2" calls
startTransition. React keeps "User 1" on screen andisPendingbecomestrue, so the example dims the area as feedback. - When the new promise resolves, React swaps in "User 2". The fallback does not appear again.
The new promise is created inside an event handler, not during render. That is the safe place to create one in a Client Component. It runs once per click and the result is stored in state, so every later render sees the same promise object.
What happens to state when a fallback appears
When a fallback replaces content that was already mounted, React hides that content instead of destroying it, and the state of components inside it is kept. When the boundary resolves, the content is shown again with its state intact. Effects in the hidden content are cleaned up while it is hidden and set up again when it returns.
On the very first render, nothing is mounted yet. A component that suspends during mount has no saved state. React discards the unfinished attempt and tries again from scratch when the data is ready. This is another reason to keep render code pure.
Common mistakes
| Symptom | Likely cause | Fix |
|---|---|---|
| Error about suspending without a boundary, or a blank page until data arrives | No `Suspense` ancestor | Add a boundary above the component that calls `use`. |
| The fallback never goes away | A new promise is created on each render, so React never sees a settled one | Keep the promise stable. See the chapter on promise identity. |
| Fast sections wait for a slow one | One large boundary | Split into smaller boundaries. |
| The page flashes the fallback on every update | The update is not in a transition | Wrap the state change in `startTransition`, or use `useDeferredValue`. |
| A boundary placed inside the component that calls `use` has no effect | The boundary is below the suspending call | Move the boundary to a parent component. |
| A rejected promise shows a blank page or crashes the tree | No error boundary | Add an error boundary. See the chapter on rejected promises. |
A short checklist
Use this before shipping a component that calls use on a promise:
- Is there a
Suspenseboundary above it? - Does the fallback fit the space the content will take?
- Do independent regions have their own boundaries?
- Are updates that replace the promise wrapped in a transition, when you don't want the old content hidden?
- Is the code above
usefree of side effects? - Is there an error boundary above the
Suspenseboundary for the rejected case?
Exercise
A page has a Suspense boundary containing <Header /> and <Feed />. Header uses a promise that resolves in 300 ms. Feed uses a promise that resolves in 3 seconds. Users complain that the page looks empty for three seconds. Describe two ways to change the boundaries so the header appears after about 300 ms.
Show answer
First, give each component its own boundary, for example <Suspense fallback={<HeaderSkeleton />}><Header /></Suspense> and <Suspense fallback={<FeedSkeleton />}><Feed /></Suspense>. Second, nest the slow part, so <Header /> stays directly in the outer boundary and <Feed /> sits in an inner Suspense. Then only the feed is covered by its own fallback. In both versions the header stops waiting for the feed.
Exercise
This component never shows its fallback, and the app shows an error or a blank screen while data loads. What is wrong, and how do you fix it? function Profile({ userPromise }) { const user = use(userPromise); return ( <Suspense fallback={<p>Loading...</p>}> <h2>{user.name}</h2> </Suspense> ); }
Show answer
The Suspense boundary is inside Profile, but use is called in Profile itself, outside the boundary. The suspension goes to the nearest boundary above Profile, and if there is none it fails. Move the boundary to the parent: <Suspense fallback={<p>Loading...</p>}><Profile userPromise={userPromise} /></Suspense>, and have Profile just return the <h2>.
Exercise
In the user-switching example, a click on "User 2" without startTransition replaces the profile with "Loading profile..." for a second. What does startTransition change, and when would a fallback still appear during a transition?
Show answer
With startTransition, React keeps the current, already-visible profile on screen while the new promise is pending, and isPending from useTransition lets you show feedback such as dimming. A fallback still appears if the boundary has no content yet, for example on its first mount, because the transition only protects content that has already been revealed.