Suspense vs Error Boundary
- Suspense: Handles loading states for lazy-loaded components or data fetching.
- Error Boundary: Catches runtime errors in component tree and displays fallback UI.
Suspense Example
import React, { Suspense, lazy } from "react";
const LazyComponent = lazy(() => import("./LazyComponent"));
function App() {
return (
<Suspense fallback={<h2>Loading...</h2>}>
<LazyComponent />
</Suspense>
);
}
export default App;
✅ Suspense shows fallback while the component is loading.
Error Boundary Example
import React from "react";
class ErrorBoundary extends React.Component {
state = { hasError: false };
static getDerivedStateFromError() {
return { hasError: true };
}
render() {
if (this.state.hasError) return <h2>Something went wrong.</h2>;
return this.props.children;
}
}
function Buggy() {
throw new Error("Crash!");
}
function App() {
return (
<ErrorBoundary>
<Buggy />
</ErrorBoundary>
);
}
✅ Prevents the app from crashing and shows fallback UI.
Key Differences
| Feature | Suspense | Error Boundary |
|---|---|---|
| Purpose | Handles lazy-loading state | Handles runtime errors |
| Fallback | Loading indicator | Error UI |
| Scope | Lazy components | Component subtree |
| Usage | With lazy & Suspense | Class components only |
Conclusion
Use Suspense for loading states and Error Boundary for error handling, making React apps robust and user-friendly.
Citations
https://savanka.com/category/learn/react/
https://www.w3schools.com/REACT/DEFAULT.ASP