Skip to main content

suspense/react-suspense

· 3 min read

slug: react-suspense title: react Suspense tags: [React]

hello apple

<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>
);
}

tip

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.

  1. Data fetching with Suspense-enabled frameworks like Relay and Next.js, such as useLazyQuery in Relay
  2. Lazy-loading component code with lazy
  3. 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.

Image

Revealing nested content as it loads

Each Suspense boundary's fallback will be filled in as the next level of content becomes available.

Image

With this change, displaying the Biography doesn't need to "wait" for the Albums to load.

AlbumsGlimmer

Let's break it down with proper sequence:

  1. If Biography hasn't loaded yet, BigSpinner is shown in place of the entire content area.
  2. Once the Biography finishes loadingm BigSpinner is replaced by the content.
  3. If Albums hasn't loaded yet, AlbumsGlimmer id shown in place of Albums and its parent Panel.
  4. Finally, once Albums finishes loading, it replaces AlbumsGlimmer.

More usage see at react <Suspense>