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;
}
}What the code does
TypeScript React Error Boundary keeps everything in the class ErrorBoundary.
Reach for react and what you get is Component, type ReactNode — that is the whole API contact area.
Emits through the .error level methods with structured payloads, so downstream transports can route by level and field.
A fresh value is allocated for the result; the arguments stay untouched.
Caveats
- Dependency check:
react— not built-in, must be present in the project.
Applying it
Running the file prints labeled results such as Boundary: — each operation’s effect is visible in the output.
Statements that matter
static getDerivedStateFromError(): State { return { hasError: true }; }
return this.state.hasError ? this.props.fallback : this.props.children;
FAQ
- Which packages must be installed first?
- Yes. The imports resolve to `react`, which the package manager must provide.
Report a problem with this exampleOpens a pre-filled issue on GitHub.