Managing Asynchronous Behavior with React Suspense

React Suspense is introduced in React 16 and it is used for handling of loading states when fetching data or lazy-loading components in React applications.

Suspense

React Suspense is a component that allows you to suspend rendering while some asynchronous work is being done, such as data fetching or lazy-loading components. It enables you to declaratively define loading states in your application, making it easier to manage asynchronous behaviour.

Fallback:

The fallback prop is a feature of Suspense that allows you to specify what content to display while the suspended component is loading.

import React from 'react';

function DataFetching() {
  return <div>Data Fetching</div>;
}

export default DataFetching;

Implement like this in App.js file.

import React, { Suspense } from 'react';
import ./../DataFetching.jsx;

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

export default App;

Leave a comment

Your email address will not be published. Required fields are marked *