Error Boundaries
What Are Error Boundaries?
A class component that catches errors from a child tree, preventing the entire application from crashing.
Lifecycle Methods
import { Component } from 'react';
class ErrorBoundary extends Component {
state = { hasError: false, error: null };
static getDerivedStateFromError(error) {
return { hasError: true, error };
}
componentDidCatch(error, info) {
console.error('Error:', error, info.componentStack);
}
render() {
if (this.state.hasError) {
return (
<div>
<h2>An Error Occurred</h2>
<p>{this.state.error?.message}</p>
<button onClick={() => this.setState({ hasError: false })}>
Try Again
</button>
</div>
);
}
return this.props.children;
}
}
Usage
<ErrorBoundary>
<WidgetA />
</ErrorBoundary>
<ErrorBoundary>
<WidgetB />
</ErrorBoundary>
Wrap each separate section so errors stay isolated.
Limitations
| Area | Caught? |
|---|---|
| Render, lifecycle, constructor | Yes |
| Event handlers | No |
| Async code (setTimeout, Promise) | No |
For event handlers, use try-catch directly.
const handleClick = () => {
try { riskyOperation(); }
catch (e) { console.error(e); }
};
Error boundaries can only be written as class components. Next chapter: Optimizing Performance.