Interview frequency: …
Short answer
They are special components that catch JavaScript errors in their descendant component tree during Render and lifecycle methods, showing a Fallback UI instead of crashing the entire application.
Explanation
Create an Error Boundary as a Class Component implementing getDerivedStateFromError (to update state and show a fallback) or componentDidCatch (to log error details to monitoring services). Error Boundaries do not catch Event Handler errors or asynchronous operations such as setTimeout.
Code example
import React, { Component, 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(error: Error, info: React.ErrorInfo) {
console.error("Error caught by the boundary:", error, info.componentStack);
}
render() {
if (this.state.hasError) return this.props.fallback;
return this.props.children;
}
}Common mistakes
- Trying to use try/catch inside returned JSX to handle errors while rendering child components.