JavaScript errors inside component rendering functions used to corrupt React's internal state and crash the entire application, resulting in a blank white screen.
An Error Boundary is a React class component that catches JavaScript errors anywhere in its child component tree, logs the errors, and displays a graceful fallback UI instead of crashing the app.
Error boundaries implement two specialized class lifecycle methods:
static getDerivedStateFromError(error): Updates state so the next render displays fallback UI.componentDidCatch(error, errorInfo): Logs exception stack traces to external monitoring services (Sentry, LogRocket).import React, { Component } from 'react';
export class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { hasError: false, error: null };
}
static getDerivedStateFromError(error) {
// Update state to render fallback UI on next render
return { hasError: true, error };
}
componentDidCatch(error, errorInfo) {
console.error('Uncaught error caught by boundary:', error, errorInfo);
}
render() {
if (this.state.hasError) {
return (
<div className="error-fallback">
<h2>Something went wrong.</h2>
<p>{this.state.error?.message}</p>
<button onClick={() => window.location.reload()}>Reload Page</button>
</div>
);
}
return this.props.children;
}
}
export default function DashboardApp() {
return (
<div className="app">
<Header />
<ErrorBoundary>
<ComplexDataGrid />
</ErrorBoundary>
</div>
);
}
Error boundaries do not catch errors for:
onClick={() => throw Error()}) — use try...catch inside event functions.setTimeout, fetch API requests).Why must Error Boundaries be implemented as Class Components rather than Functional Components in current React versions?
Sign in to track your learning journey, earn industry-recognized certificates, and join our elite developer community.
Quick Access With