Global Error Boundaries
Overview
Global error boundaries are a way to catch JavaScript errors anywhere in the React component tree, log those errors, and display a fallback UI instead of crashing the application.
Creating a Global Error Boundary
Step 1: Create an Error Boundary Component
Create a GlobalErrorBoundary.jsx
file:
import React from "react";
class GlobalErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
// Update state to trigger fallback UI
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
// Log the error details
console.error("Error occurred:", error, errorInfo);
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong. Please try again later.</h1>;
}
return this.props.children;
}
}
export default GlobalErrorBoundary;
Step 2: Wrap Your Application with the Error Boundary
Wrap your App component with the error boundary in index.js
or App.js
:
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import GlobalErrorBoundary from "./GlobalErrorBoundary";
ReactDOM.render(
<GlobalErrorBoundary>
<App />
</GlobalErrorBoundary>,
document.getElementById("root")
);
Benefits of Using Error Boundaries
- Prevents the application from crashing due to unhandled errors.
- Provides a user-friendly fallback UI.
- Logs error details for debugging.