Q15: What are Error Boundaries and what types of errors can they catch?
Error Boundaries are React Class Components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI. They catch errors during rendering, lifecycle methods, and constructors. They do NOT catch errors in event handlers, async code, SSR, or unhandled promise rejections.
Class Error Boundary Implementation
class ErrorBoundary extends React.Component {
state = { hasError: false };
static getDerivedStateFromError(error) {
return { hasError: true }; // Render fallback UI
}
componentDidCatch(error, errorInfo) {
logErrorToService(error, errorInfo);
}
render() {
if (this.state.hasError) return <h1>Something went wrong.</h1>;
return this.props.children;
}
}Wrapping components inside ErrorBoundary safely catches rendering errors and displays fallback UI.
Key Takeaways
Defined using class methods
static getDerivedStateFromError()orcomponentDidCatch().Prevents whole component tree unmounting due to uncaught rendering errors.
Knowledge Check
Which type of error CANNOT be caught by a React Error Boundary?