Error Boundaries
Catching errors, fallback UIs, error reporting, and graceful degradation.
Overview
Error boundaries catch JavaScript errors in their child component tree and display fallback UI.
Key Concepts
- componentDidCatch — Catches errors during rendering
- getDerivedStateFromError — Updates state when error occurs
- Fallback UI — User-friendly error display
- Error Reporting — Log errors to monitoring services
- Granular Boundaries — Wrap specific sections, not entire app
Code Examples
import { Component } from 'react';
class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { hasError: false, error: null };
}
static getDerivedStateFromError(error) {
return { hasError: true, error };
}
componentDidCatch(error, errorInfo) {
console.error('Error caught:', error, errorInfo);
// Send to error reporting service
}
render() {
if (this.state.hasError) {
return (
<div className="error-fallback">
<h2>Something went wrong</h2>
<p>{this.state.error?.message}</p>
<button onClick={() => this.setState({ hasError: false })}>
Try again
</button>
</div>
);
}
return this.props.children;
}
}
// Usage
function App() {
return (
<ErrorBoundary>
<Header />
<main>
<ErrorBoundary>
<Sidebar />
</ErrorBoundary>
<Content />
</main>
</ErrorBoundary>
);
}
Practice
Create an error boundary that logs errors and provides a retry mechanism.