slug: react-suspense title: react Suspense tags: [React]
- apple
- orange
hello apple
hello orange
<Suspense>
<Suspense> component is part of React's Concurrent Mode feature to improve the user experience by making it more respective and resilient.
Purpose
The primary purpose of the <Suspense> component is to handle asynchronous operations, such as data fetching or lazy loading of components, in a more declarative way. It allows you to "suspend" rendering until some condition is met, typically until data is ready.
import React, { Suspense } from 'react';
const MyComponent = React.lazy(() => import('./MyComponent'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<MyComponent />
</Suspense>
);
}
When you are using Relay's useLazyQuery , the official document recommend wrap it with a Suspense Component for better user experience.
Common usage
Displaying a fallback while content is loading
<Suspense fallback={<Loading />}>
<Albums />
</Suspense>
React will display loading fallback until all the code and data needed by the children has been loaded.
Only Suspense-enable data sources will activate the Suspense component.
- Data fetching with Suspense-enabled frameworks like Relay and Next.js, such as useLazyQuery in Relay
- Lazy-loading component code with lazy
- Reading the value of a Promise with use
Revealing content together at once
By default, the whole tree inside Suspense is treated as a single unit. Only all components inside the Suspense have been ready for rendering, all of those components will appear at once. Otherwise, even if only one of these components suspends waiting for some data, all of them together will be replaced by the loading indicator.
Revealing nested content as it loads
Each Suspense boundary's fallback will be filled in as the next level of content becomes available.
With this change, displaying the Biography doesn't need to "wait" for the Albums to load.
AlbumsGlimmerLet's break it down with proper sequence:
- If Biography hasn't loaded yet, BigSpinner is shown in place of the entire content area.
- Once the Biography finishes loadingm BigSpinner is replaced by the content.
- If Albums hasn't loaded yet, AlbumsGlimmer id shown in place of Albums and its parent Panel.
- Finally, once Albums finishes loading, it replaces AlbumsGlimmer.