DEV Community


Posted on

How to use React <Suspense>

React Suspense is a feature introduced in React to simplify the handling of asynchronous operations like data fetching or code splitting. Here's a basic guide on how to use it:

  1. Code Splitting with React.lazy:
    • Use React.lazy to dynamically import a component. This helps split your code into chunks that are loaded only when needed.
   const SomeComponent = React.lazy(() => import('./SomeComponent'));
Enter fullscreen mode Exit fullscreen mode
  1. Wrap with <Suspense> Component:
    • Wrap the lazily loaded component with the <Suspense> component.
    • Provide a fallback UI to display while the component is being loaded.
   import React, { Suspense } from 'react';

   function MyComponent() {
     return (
       <Suspense fallback={<div>Loading...</div>}>
         <SomeComponent />
Enter fullscreen mode Exit fullscreen mode
  1. Handling Data Fetching:

    • For data fetching, you can use libraries like Relay or others that support Suspense.
    • Wrap the component that performs data fetching inside <Suspense>.
    • The fallback will be displayed until the data fetching is complete.
  2. Error Boundaries:

    • Use error boundaries to handle errors in asynchronous code. Suspense boundaries only handle loading states, not errors.
    • Wrap your Suspense component in an error boundary to catch and handle errors gracefully.
  3. Server Side Rendering (SSR):

    • If using SSR, ensure your server-rendering environment supports Suspense.
    • Libraries like Next.js have built-in support for Suspense with SSR.
  4. Use with Concurrent Mode (Experimental):

    • Suspense works best with React's Concurrent Mode, which is still experimental.
    • Concurrent Mode allows for more fine-grained control over the rendering process, improving performance for complex applications.
  5. Testing:

    • When writing tests for components using Suspense, make sure to mock the loading state and test the fallback UI.
    • Also, test the loaded state to ensure the component renders ``correctly after the asynchronous operation completes.

Top comments (0)