Error Boundaries are class components that catch JavaScript errors in their child component tree, log them, and display fallback UI. They don't catch errors in event handlers, async code, SSR, or errors thrown in the boundary itself.
What Error Boundaries Do:
Limitations (don't catch):
Implementation:
Best Practices:
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false, error: null };
}
// Update state to show fallback UI
static getDerivedStateFromError(error) {
return { hasError: true, error };
}
// Log error information
componentDidCatch(error, errorInfo) {
console.error('Error caught:', error);
console.error('Component stack:', errorInfo.componentStack);
// Send to error monitoring service
logErrorToService(error, errorInfo);
}
render() {
if (this.state.hasError) {
return this.props.fallback || (
<div className="error-fallback">
<h2>Something went wrong</h2>
<button onClick={() => this.setState({ hasError: false })}>
Try again
</button>
</div>
);
}
return this.props.children;
}
}
// Usage
function App() {
return (
<ErrorBoundary fallback={<ErrorPage />}>
<MainContent />
</ErrorBoundary>
);
}