Blog>
Snippets

Setting Up Suspense Boundary

Demonstrate how to establish a Suspense boundary within a React component, utilizing the <Suspense> component to wrap another component that fetches data.
import React, { Suspense } from 'react';
First, import Suspense along with React.
const LazyComponent = React.lazy(() => import('./LazyComponent'));
Define a lazy-loaded component using React.lazy for dynamic import.
function MyComponent() {
Start defining a functional component that will utilize Suspense.
  return (
The return statement begins the JSX structure of the functional component.
    <Suspense fallback={<div>Loading...</div>}>
Wrap the lazy-loaded component in a Suspense boundary specifying a fallback UI during loading.
      <LazyComponent />
Place the lazy-loaded component that fetches data inside the Suspense boundary.
    </Suspense>
Close the Suspense boundary.
  );
Close the return statement.
}
Close the functional component definition.
export default MyComponent;
Export the newly defined component with Suspense boundary.