Problem Overview
Error boundaries are a powerful feature in React that helps developers handle JavaScript errors gracefully in their component tree. By implementing error boundaries, you can prevent the entire application from crashing and provide a fallback UI instead.
To create an error boundary, you need to define a class component that implements either static getDerivedStateFromError() or componentDidCatch() methods. Here's an example:
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
// Log the error to an error reporting service
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}To use your ErrorBoundary, simply wrap any component that you want to protect:
<ErrorBoundary>
<MyComponent />
</ErrorBoundary>Remember that error boundaries only catch errors in the components below them in the tree. They don't catch errors for:
- Event handlers
- Asynchronous code (e.g., setTimeout or promises)
- Server-side rendering
By utilizing error boundaries, you can improve the user experience by displaying a friendly message instead of a broken UI.