Skip to main content

Suspense

Suspend rendering while loading asynchronous data or code. Display a fallback UI until the suspended content is ready.

Suspense Component

Signature

ComponentChildren
The content to render once data is loaded.
ComponentChildren
The fallback UI to show while suspended (typically a loading indicator).

Usage

lazy

Lazy load components for code splitting.

Signature

() => Promise<{ default: T }>
required
A function that returns a Promise resolving to a module with a default export containing the component.
T
A lazy-loaded component that can be rendered like a normal component.

Usage

Complete Examples

Lazy Loading Routes

Multiple Lazy Components

Nested Suspense

Data Fetching with Suspense

Implementation Details

Suspense Component

The Suspense implementation:

lazy Function

The lazy implementation:

How Suspense Works

  1. Promise Thrown: A component throws a Promise when data isn’t ready
  2. Suspense Catches: Nearest Suspense boundary catches the Promise
  3. Fallback Shown: Suspense renders the fallback prop
  4. Promise Resolves: When the Promise resolves, the component re-renders
  5. Content Displayed: Real content replaces the fallback

Error Boundaries with Suspense

Combine with error boundaries for error handling:

Fallback Components

Simple Loader

Skeleton Screen

Best Practices

  1. Granular Suspense: Use multiple Suspense boundaries for better UX
  2. Meaningful Fallbacks: Show skeleton screens instead of generic spinners
  3. Error Boundaries: Always wrap Suspense in error boundaries
  4. Loading States: Consider showing partial content while loading
  5. Code Splitting: Use lazy for route-based code splitting

Transition to Loaded Content

Use CSS for smooth transitions:

useTransition Hook

For smoother transitions between loading states:

Source

Implementation: compat/src/suspense.js:1-255