Error Boundaries
6 min read
Catching Runtime Errors in the Component Tree
Error boundaries are class components that implement componentDidCatch and getDerivedStateFromError. They catch JavaScript errors anywhere in their child tree and display a fallback UI instead of crashing the whole app.
jsx
import { Component } from 'react';
class ErrorBoundary extends Component {
state = { hasError: false, message: '' };
static getDerivedStateFromError(error) {
return { hasError: true, message: error.message };
}
componentDidCatch(error, info) {
console.error('Caught by boundary:', error, info.componentStack);
}
render() {
if (this.state.hasError) {
return <p>Something went wrong: {this.state.message}</p>;
}
return this.props.children;
}
}
// Usage
<ErrorBoundary>
<RiskyWidget />
</ErrorBoundary>Error boundaries are one of the few remaining use cases for class components. The community package react-error-boundary provides a modern, hook-friendly API so you don't have to write the class yourself.
Ready to test yourself?
Practice React— quiz & coding exercises