React Suspense helps manage loading states while components or data are being loaded asynchronously. The fallback UI is shown until the suspended content becomes available.
Suspense works by suspending rendering when a component is not ready. React then displays the fallback UI until the promise resolves.
// App.js - Basic Suspense usage with lazy loading
import React, { lazy, Suspense } from "react";
const Profile = lazy(() => import("./Profile"));
function App() {
return (
<div className="text-center p-3">
<h4>React Suspense Example</h4>
<Suspense fallback={<p>Loading Profile...</p>}>
<Profile />
</Suspense>
</div>
);
}
export default App;
The fallback can be any React element such as text, spinner, or skeleton.
// LoadingSpinner.js - Reusable fallback component
import React from "react";
function LoadingSpinner() {
return (
<div className="d-flex justify-content-center align-items-center" style={{height: "100px"}}>
<div className="spinner-border text-primary" role="status">
<span className="visually-hidden">Loading...</span>
</div>
</div>
);
}
export default LoadingSpinner;
// Using custom fallback inside Suspense
<Suspense fallback={<LoadingSpinner />}>
<Profile />
</Suspense>
// Multiple Suspense boundaries for independent loading
<div>
<Suspense fallback={<div>Loading Sidebar...</div>}>
<Sidebar />
</Suspense>
<Suspense fallback={<div>Loading Main Content...</div>}>
<MainContent />
</Suspense>
</div>
// ErrorBoundary.js - Handles component load errors
import React from "react";
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError() {
return { hasError: true };
}
render() {
if (this.state.hasError) {
return <h4 className="text-danger">Something went wrong while loading.</h4>;
}
return this.props.children;
}
}
export default ErrorBoundary;
// Wrapping Suspense with ErrorBoundary
<ErrorBoundary>
<Suspense fallback={<LoadingSpinner />}>
<Profile />
</Suspense>
</ErrorBoundary>
Flow: Component Requested → Suspended → Fallback UI → Component Loaded → UI Rendered
Click the button to simulate a network request. Watch how the Fallback (Skeleton) appears instantly, and is then replaced by the Profile Component.
While the component is loading, users see the fallback UI. Once loaded, the actual component replaces the fallback seamlessly.