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
- Loading States:
Suspense
allows you to define a fallback UI (like a loading spinner) to be displayed while the main content is being loaded. - Concurrent Rendering: It enables React to pause rendering while waiting for data to be fetched and to resume rendering once the data is available.
- Data Fetching:
Suspense
works in conjunction with React’suseTransition
and other data-fetching libraries likeReact.lazy
for code-splitting andreact-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:
React.lazy
is used to dynamically import theLazyComponent
.Suspense
is used to wrap theLazyComponent
and provides a fallback UI (<div>Loading...</div>
) that is displayed while the component is being loaded.
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:
DataComponent
is dynamically loaded, simulating data fetching.- The
fetchData
function returns a promise that resolves after 2 seconds. Suspense
wrapsDataComponent
and displays a fallback UI while waiting for the data to load.
Published on: Jul 21, 2024, 11:00 AM