Home  Reactjs   How to use ...

How to use suspense component in react

The Suspense component in React is a feature that allows you to handle the loading states of components that rely on asynchronous data fetching. It is part of React's built-in functionality for concurrent rendering, which aims to make it easier to build applications that are fast and responsive even when dealing with complex data dependencies.

Key Concepts of Suspense

  1. Loading States: Suspense allows you to define a fallback UI (like a loading spinner) to be displayed while the main content is being loaded.
  2. Concurrent Rendering: It enables React to pause rendering while waiting for data to be fetched and to resume rendering once the data is available.
  3. Data Fetching: Suspense works in conjunction with React’s useTransition and other data-fetching libraries like React.lazy for code-splitting and react-fetch for data fetching.

Basic Usage

Here’s a basic example demonstrating how to use Suspense with React.lazy for code-splitting:

Step 1: Lazy Load a Component

import React, { Suspense, lazy } from 'react';

// Dynamically import a component
const LazyComponent = lazy(() => import('./LazyComponent'));

const App = () => {
  return (
    <div>
      <h1>My App</h1>
      {/* Use Suspense to handle the loading state */}
      <Suspense fallback={<div>Loading...</div>}>
        <LazyComponent />
      </Suspense>
    </div>
  );
};

export default App;

In this example:

Usage with Data Fetching

React’s Suspense can also be used with data fetching. Here’s an example using a mock data-fetching utility:

import React, { Suspense, useState, useEffect } from 'react';

// Mock data fetching function
const fetchData = () => {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('Data fetched!');
    }, 2000);
  });
};

const DataComponent = React.lazy(async () => {
  const data = await fetchData();
  return {
    default: () => <div>{data}</div>,
  };
});

const App = () => {
  return (
    <div>
      <h1>My App</h1>
      <Suspense fallback={<div>Loading data...</div>}>
        <DataComponent />
      </Suspense>
    </div>
  );
};

export default App;

In this example:

Published on: Jul 21, 2024, 11:00 AM  
 

Comments

Add your comment