TypeScript React Error Boundary
Implement a typed error boundary in React with TypeScript that catches render errors, displays fallback UI, logs error details, and supports recovery.
Code
import { Component, type ReactNode } from 'react';
interface Props { children: ReactNode; fallback: ReactNode; }
interface State { hasError: boolean; }
class ErrorBoundary extends Component<Props, State> {
state: State = { hasError: false };
static getDerivedStateFromError(): State { return { hasError: true }; }
componentDidCatch(err: Error) { console.error('Boundary:', err); }
render() {
return this.state.hasError ? this.props.fallback : this.props.children;
}
}