Part 41: Error Boundaries: Graceful Error Handling & Fallbacks
In React, an unhandled JavaScript error inside any component unmounts the entire component tree, leaving the user with a blank white screen. Error Boundaries catch errors anywhere in their child component tree, log those errors, and display a fallback UI.
1. Creating an Error Boundary Class Component
Currently, Error Boundaries must be written as class components because they require static getDerivedStateFromError or componentDidCatch:
import React, { Component } from 'react';
export class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { hasError: false, error: null };
}
static getDerivedStateFromError(error) {
// Update state so the next render shows the fallback UI
return { hasError: true, error };
}
componentDidCatch(error, errorInfo) {
// Log error to monitoring service (e.g. Sentry, Datadog)
console.error('ErrorBoundary caught an error:', error, errorInfo);
}
handleReset = () => {
this.setState({ hasError: false, error: null });
};
render() {
if (this.state.hasError) {
if (this.props.fallback) {
return this.props.fallback({ error: this.state.error, reset: this.handleReset });
}
return (
<div className="p-6 border border-red-300 bg-red-50 rounded text-center">
<h2 className="text-xl font-bold text-red-800">Something went wrong</h2>
<p className="text-sm text-red-600 my-2">{this.state.error?.message}</p>
<button onClick={this.handleReset} className="btn-primary">
Try Again
</button>
</div>
);
}
return this.props.children;
}
}
2. Granular Error Boundaries in Practice
Place boundaries around independent widgets so a failure in one widget doesn't break the entire dashboard:
export default function Dashboard() {
return (
<div className="dashboard-grid">
<ErrorBoundary>
<SidebarNavigation />
</ErrorBoundary>
<main>
{/* Even if AnalyticsWidget crashes, the rest of the app stays working! */}
<ErrorBoundary>
<AnalyticsWidget />
</ErrorBoundary>
<ErrorBoundary>
<RecentActivityFeed />
</ErrorBoundary>
</main>
</div>
);
}
Key Takeaways
- Error Boundaries prevent total application crashes by catching rendering errors.
- Use granular boundaries around complex widgets to isolate failures.
- Forward errors to external monitoring platforms in
componentDidCatch.
In Part 42, we will explore React Portals for rendering modals, tooltips, and dropdowns!

