Sobes.tech
Middle

What is Suspense used for in React?

sobes.tech AI

Answer from AI

Suspense in React is used to manage the loading state of components that load asynchronously, such as during dynamic import or data fetching.

The main purpose of Suspense is to display a fallback UI (for example, a loading indicator) while the required component or data is being loaded.

Example usage:

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

const LazyComponent = lazy(() => import('./MyComponent'));

function App() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <LazyComponent />
    </Suspense>
  );
}

Here, LazyComponent is loaded dynamically, and until it loads, React will display <div>Loading...</div>. This improves UX by showing the user a loading progress without blocking the interface.

Suspense is also used in React Concurrent Mode to manage asynchronous operations and can work with libraries for data fetching.