Creating a Basic Error Boundary Component
You'll learn: How to build your first error boundary component using lifecycle methods to catch and handle rendering errors gracefully.
Now that you understand what error boundaries are for, let's build one. An error boundary is a special component that uses two lifecycle methods to catch JavaScript errors anywhere in their child component tree.
How It Works
Think of an error boundary like a safety net under a trapeze artist. If something goes wrong during a performance (rendering), the net catches the performer instead of letting them crash. Your error boundary catches errors during rendering, lifecycle methods, and constructors of components below it.
The Two Key Lifecycle Methods
You need two lifecycle methods to create an error boundary:
static getDerivedStateFromError(error)- Called during the render phase when an error is thrown. It lets you update state to show a fallback UI.componentDidCatch(error, errorInfo)- Called during the commit phase after an error is caught. Perfect for logging errors to an error reporting service.
Here's a basic implementation:
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
// Update state so next render shows fallback UI
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
// Log error details
console.error('Error caught:', error, errorInfo);
}
render() {
if (this.state.hasError) {
return <h2>Something went wrong.</h2>;
}
return this.props.children;
}
}
You wrap components that might error with this boundary, and if they crash, users see your fallback message instead of a blank screen.
Key Takeaway: Error boundaries use getDerivedStateFromError to display fallback UI and componentDidCatch to log errors, catching rendering failures in their child components before they break your entire app.