Error Boundaries in React
A JavaScript error in a single component should not crash the entire web application. React handles this using Error Boundaries—special components that catch runtime errors in their child component tree and display a fallback UI instead.
1. What is an Error Boundary?
An Error Boundary is a class-based component that implements either (or both) of these lifecycle methods:
- static getDerivedStateFromError(error): Updates the component state so the next render displays the fallback UI.
- componentDidCatch(error, errorInfo): Used to log error details to external error monitoring services (such as Sentry or LogRocket).
2. Implementing an Error Boundary Component
Because React hooks do not yet support error boundaries, you must use a Class Component for this setup:
import React from "react";
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
// Update state to trigger fallback render on child crash
static getDerivedStateFromError(error) {
return { hasError: true };
}
// Log details to monitoring service
componentDidCatch(error, errorInfo) {
console.error("ErrorBoundary caught an error:", error, errorInfo);
}
render() {
if (this.state.hasError) {
// Custom fallback UI
return (
<div className="error-card">
<h2>Something went wrong.</h2>
<p>Please refresh the page or try again later.</p>
</div>
);
}
// Render children if no errors occur
return this.props.children;
}
}
export default ErrorBoundary;3. Applying Error Boundaries in Your App
You can use Error Boundaries to wrap your entire application, or wrap individual sections (like widgets or sidebars) to prevent a crash in one widget from bringing down the rest of the page:
import ErrorBoundary from "./ErrorBoundary";
import WeatherWidget from "./WeatherWidget";
import MainPanel from "./MainPanel";
function App() {
return (
<div className="app-layout">
<ErrorBoundary>
<WeatherWidget />
</ErrorBoundary>
<MainPanel />
</div>
);
}If WeatherWidget throws a runtime error (for example, failing to parse a API payload), the rest of the application remains fully interactive.
4. What Error Boundaries Cannot Catch
Error boundaries do not catch errors in the following scenarios:
- Event handlers (for example, a crash inside an onClick handler). Use standard try-catch blocks here.
- Asynchronous code (such as a rejected promise inside a setTimeout or fetch callback).
- Server-side rendering (SSR).
- Errors thrown in the Error Boundary component itself (rather than its children).