What is an Error Boundary in React
An Error Boundary is a special component in React designed to handle runtime errors in a part of the component tree. It catches JavaScript errors anywhere in its child component tree, logs those errors, and displays a fallback UI instead of crashing the whole application.
Use Cases
- Prevent Application Crashes: Use Error Boundaries to prevent the entire app from crashing due to a bug in a specific component.
- Display User-Friendly Messages: Replace technical error messages with a user-friendly fallback UI
- Isolate Errors: Debug specific parts of the component tree by wrapping them with separate Error Boundaries.
- Logging Errors: Log error details to external error-tracking services (e.g., Sentry, Bugsnag).
import React from "react";
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false, error: null, errorInfo: null };
}
static getDerivedStateFromError(error) {
// Update state so the next render shows the fallback UI.
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
// Log the error to an error reporting service
console.error("Error caught by Error Boundary:", error, errorInfo);
this.setState({ error, errorInfo });
}
render() {
if (this.state.hasError) {
// Fallback UI
return (
<div>
<h1>Something went wrong.</h1>
<details style={{ whiteSpace: "pre-wrap" }}>
{this.state.error && this.state.error.toString()}
<br />
{this.state.errorInfo.componentStack}
</details>
</div>
);
}
return this.props.children;
}
}
export default ErrorBoundary;