Without error boundaries, a single component crash takes down your entire app. Error boundaries prevent cascading failures.
What Are Error Boundaries?
Error boundaries are React components that catch JavaScript errors in their child component tree, log them, and display a fallback UI.
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false, error: null };
}
static getDerivedStateFromError(error) {
return { hasError: true, error };
}
componentDidCatch(error, errorInfo) {
// Log to error reporting service
console.error("Error boundary caught:", error, errorInfo);
reportToSentry(error, { componentStack: errorInfo.componentStack });
}
render() {
if (this.state.hasError) {
return this.props.fallback || <DefaultErrorUI error={this.state.error} />;
}
return this.props.children;
}
}Usage Patterns
Page-Level Boundary
<ErrorBoundary fallback={<FullPageError />}>
<App />
</ErrorBoundary>Feature-Level Boundary
function Dashboard() {
return (
<div className="grid grid-cols-3 gap-4">
<ErrorBoundary fallback={<WidgetError name="Revenue" />}>
<RevenueChart />
</ErrorBoundary>
<ErrorBoundary fallback={<WidgetError name="Users" />}>
<UserStats />
</ErrorBoundary>
<ErrorBoundary fallback={<WidgetError name="Orders" />}>
<OrderTable />
</ErrorBoundary>
</div>
);
}
// If OrderTable crashes, Revenue and Users still work!Retry Pattern
function ErrorFallback({ error, resetErrorBoundary }) {
return (
<div className="error-panel">
<h2>Something went wrong</h2>
<pre>{error.message}</pre>
<button onClick={resetErrorBoundary}>Try Again</button>
</div>
);
}
// With react-error-boundary library
import { ErrorBoundary } from "react-error-boundary";
<ErrorBoundary
FallbackComponent={ErrorFallback}
onReset={() => queryClient.invalidateQueries()}
resetKeys={[userId]} // Auto-reset when userId changes
>
<UserProfile userId={userId} />
</ErrorBoundary>What Error Boundaries DON'T Catch
- Event handlers (use try/catch inside handlers)
- Async code (promises, setTimeout)
- Server-side rendering
- Errors in the error boundary itself
Production Strategy
- App-level boundary: catches everything, shows "refresh" page
- Route-level boundary: isolates page crashes
- Feature-level boundary: isolates widget crashes
- Always log errors to a monitoring service (Sentry, DataDog)