Error Boundary with Fallback UI
Class-based error boundary component that catches render errors and displays a customizable fallback UI.
import React from 'react';
interface Props {
children: React.ReactNode;
fallback?: React.ReactNode;
}
interface State {
hasError: boolean;
error: Error | null;
}
export class ErrorBoundary extends React.Component<Props, State> {
constructor(props: Props) {
super(props);
this.state = { hasError: false, error: null };
}
static getDerivedStateFromError(error: Error): State {
return { hasError: true, error };
}
componentDidCatch(error: Error, info: React.ErrorInfo) {
console.error('ErrorBoundary caught:', error, info.componentStack);
}
render() {
if (this.state.hasError) {
if (this.props.fallback) return this.props.fallback;
return (
<div role="alert" style={{ padding: 16 }}>
<h2>Something went wrong</h2>
<pre style={{ whiteSpace: 'pre-wrap' }}>
{this.state.error?.message}
</pre>
<button onClick={() => this.setState({ hasError: false, error: null })}>
Try again
</button>
</div>
);
}
return this.props.children;
}
}
// Usage:
// <ErrorBoundary fallback={<p>Oops!</p>}>
// <RiskyComponent />
// </ErrorBoundary>Use Cases
- Graceful error recovery
- Production crash reporting
- Wrapping third-party components
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
Portal-Based Modal Component
Accessible modal component using React portals with focus trapping, Escape key close, and backdrop click.
usePrevious Hook
Track the previous value of any state or prop using a ref-based hook for comparison logic.
Async Error Handler Wrapper
Higher-order function that wraps async Express route handlers and forwards rejected promises to error middleware.
Retry Decorator with Exponential Backoff
Generic retry decorator with configurable attempts, exponential backoff, and exception filtering.