Suspense for Data Fetching
Relevant source files
The following files were used as context for generating this wiki page:
- packages/react-reconciler/src/ReactFiberSuspenseComponent.js
- packages/react-reconciler/src/ReactFiberThenable.js
- packages/react-reconciler/src/tests/ReactSuspense-test.internal.js
- packages/react-dom/src/tests/ReactDOMFizzServer-test.js
- packages/react-reconciler/src/tests/ReactSuspenseList-test.js
- packages/react-reconciler/src/tests/ReactSuspenseEffectsSemantics-test.js
- packages/react-reconciler/src/tests/ReactUse-test.js
Suspense for Data Fetching is a mechanism in React that allows components to declaratively "wait" for asynchronous operations, such as data fetching or code loading, to complete before they render. When a component in a <Suspense> tree suspends, React pauses its rendering, displays a fallback UI, and automatically resumes rendering once the required data is available. This provides a streamlined way to manage loading states directly within the component model.
The core mechanism involves a component throwing a promise-like object, known as a "thenable". React's reconciler catches this thenable and traverses up the fiber tree to find the nearest <Suspense> boundary. It then displays the fallback prop of that boundary. Once the thenable resolves, React schedules a re-render of the suspended component, attempting to render its content again. This process is integrated with React's concurrent rendering capabilities, allowing for non-blocking UI updates and better user experiences during data loading.
Core Concepts
The <Suspense> Component
The <Suspense> component is the primary API for using this feature. It takes a fallback prop, which is a React element to be displayed while any of its children are suspended.
children: The primary content that may suspend.fallback: The UI to show while the primary content is loading. This can benullorundefinedto render nothing.
Sources: packages/react-reconciler/src/tests/ReactSuspenseFallback-test.js:101-115
Triggering Suspension with React.use()
A component suspends by reading the value of a promise using the React.use() hook. If the promise is still pending, the use hook throws the promise, which is caught by the React runtime to trigger the Suspense mechanism. If the promise has resolved, use returns the fulfilled value. If it has rejected, use throws the rejection reason.
// Example of a component that suspends
function AsyncText({text}) {
// getAsyncText returns a promise
const promise = getAsyncText(text);
// `use` will suspend if the promise is pending
const resolvedText = use(promise);
return <Text text={resolvedText} />;
}
Sources: packages/react-reconciler/src/tests/ReactUse-test.js:132-148
Thenable Tracking
When a promise is thrown, React's reconciler wraps it in an internal Thenable structure to track its status (pending, resolved, or rejected). This allows React to attach listeners to the promise and know when to retry rendering the suspended component without relying on a global cache.
This diagram illustrates the internal states of a Thenable as tracked by React.
Rendering Lifecycle
The rendering lifecycle with Suspense involves several key stages, from initial suspension to final content resolution.
Initial Mount and Suspension Flow
This diagram shows the sequence of events when a component suspends during its initial mount.
- A component calls
use(promise)where the promise is pending. - The component "suspends" by throwing the promise.
- React catches the promise and walks up the tree to find the nearest
<Suspense>boundary. - React renders the
fallbackUI of that boundary. The original component tree is kept aside but not mounted. - When the promise resolves, React schedules a new render.
- React retries rendering the original component. This time,
use(promise)returns the resolved value, and rendering completes successfully. - The fallback UI is replaced with the actual component content.
Sources: packages/react-reconciler/src/tests/ReactSuspense-test.internal.js:82-120
Effects and Refs Handling
When a component tree is suspended, its effects and refs are not mounted. If an already-mounted tree re-suspends, its effects and refs are cleaned up (destroyed).
useLayoutEffect/componentDidMount: These are not fired for a suspended tree. When the tree is shown again, they are fired as if it were a new mount.useEffect: Passive effects follow the same logic.refcallbacks: Refs are detached when a tree is hidden and re-attached when it is shown again.
This ensures that effects and refs do not operate on an incomplete or hidden DOM tree.
Sources: packages/react-reconciler/src/tests/ReactSuspenseEffectsSemantics-test.js:341-396, packages/react-reconciler/src/tests/ReactSuspenseEffectsSemantics-test.js:1200-1256
Server-Side Rendering (SSR) with Suspense
React's Fizz server renderer has built-in support for <Suspense>, enabling streaming server-rendered HTML.
When a component suspends on the server:
- The server sends the initial HTML shell, including the
fallbackUI for the<Suspense>boundary. - The server continues to render other parts of the page.
- Once the promise for the suspended component resolves on the server, React streams the final HTML for that component.
- This chunk of HTML is accompanied by an inline
<script>tag that finds the fallback content on the client and replaces it with the newly streamed HTML.
This diagram illustrates the streaming SSR process with Suspense.
If a server render for a boundary fails, a client-render instruction is sent instead, allowing the client to take over and render the boundary.
Sources: packages/react-dom/src/tests/ReactDOMFizzServer-test.js:485-520, packages/react-dom/src/tests/ReactDOMFizzServer-test.js:655-731
<SuspenseList> for Coordination
The <SuspenseList> component coordinates the reveal order of multiple adjacent <Suspense> or React.lazy components. This is useful for preventing a jarring user experience where UI elements pop in one by one.
Sources: packages/react-reconciler/src/tests/ReactSuspenseList-test.js
revealOrder Prop
The revealOrder prop controls the order in which the children of a SuspenseList are revealed after their content has loaded.
revealOrder Value | Description |
|---|---|
independent | (Default-like behavior) Each child is revealed as soon as it's ready, without coordinating with siblings. |
together | All children are revealed at the same time, only after all of them are ready. |
forwards | Children are revealed in the order they appear in the tree (top to bottom). A child will not reveal until all preceding siblings are revealed. |
unstable_legacy-backwards | Children are revealed in the reverse order they appear in the tree (bottom to top). |
Sources: packages/react-reconciler/src/tests/ReactSuspenseList-test.js:248-301, packages/react-reconciler/src/tests/ReactSuspenseList-test.js:304-361, packages/react-reconciler/src/tests/ReactSuspenseList-test.js:705-758, packages/react-reconciler/src/tests/ReactSuspenseList-test.js:811-864
tail Prop
The tail prop, used with revealOrder="forwards" or revealOrder="backwards", configures how fallbacks for unloaded items are shown.
tail Value | Description |
|---|---|
visible | (Default) All fallbacks are shown. |
collapsed | Only the next fallback in the list is shown. |
hidden | No fallbacks are shown. |
Sources: packages/react-reconciler/src/tests/ReactSuspenseList-test.js:1152-1205, packages/react-reconciler/src/tests/ReactSuspenseList-test.js:1499-1547
Summary
Suspense for Data Fetching provides a powerful, declarative model for handling asynchronous operations in React. By throwing promises from components and using <Suspense> boundaries, developers can manage loading states without manual state management, leading to cleaner code and a better user experience. The integration with concurrent rendering and streaming SSR makes it a cornerstone of modern React application architecture.