Clean β’ Professional
React Suspense is a powerful feature introduced to help developers manage lazy loading components and handle asynchronous operations in the UI. It improves performance by loading only whatβs needed and providing a smooth user experience.
Using Suspense, you can delay rendering parts of your UI until certain conditions are met, like fetching data or loading components.
In a typical React application, all components render at once, which can lead to slower page load times, especially for large apps.
React Suspense allows you to:
React provides the React.lazy() function to dynamically import components.
Syntax:
const Component = React.lazy(() => import('./Component'));
React.lazy() takes a function that returns a dynamic import.Example: Lazy Loading a Component
import React, { Suspense } from "react";
const LazyComponent = React.lazy(() => import("./LazyComponent"));
function App() {
return (
<div>
<h1>React Suspense Example</h1>
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
</div>
);
}
export default App;
<Suspense> wraps the lazy-loaded component.fallback defines the UI shown while the component is loading.You can wrap multiple lazy components in a single Suspense:
<Suspense fallback={<div>Loading components...</div>}>
<LazyHeader />
<LazyContent />
<LazyFooter />
</Suspense>
React 18 introduced support for asynchronous data fetching with Suspense, especially with libraries like React Query or Relay.
Example using a mock async component:
import React, { Suspense } from "react";
const AsyncComponent = React.lazy(() =>
new Promise(resolve => {
setTimeout(() => resolve(import("./AsyncComponent")), 3000);
})
);
function App() {
return (
<div>
<h1>Async Component with Suspense</h1>
<Suspense fallback={<div>Loading async content...</div>}>
<AsyncComponent />
</Suspense>
</div>
);
}
export default App;
setTimeout simulates a network delay.