Error Boundaries protect a React UI from certain rendering errors in descendant components. They let an application show a fallback screen instead of losing the entire visible application when a component throws during rendering.
What an Error Boundary does
An Error Boundary catches errors during rendering and related React lifecycle work in its child tree and renders fallback UI. It does not catch every possible JavaScript error in the application.
flowchart TD
A[Component tree] --> B[Child component throws]
B --> C[Error Boundary]
C --> D[Fallback UI]
C --> E[Log error]
Class-based boundary
class ErrorBoundary extends React.Component {
state = {
hasError: false
};
static getDerivedStateFromError() {
return { hasError: true };
}
componentDidCatch(error, info) {
console.error(error, info);
}
render() {
if (this.state.hasError) {
return <h2>Something went wrong.</h2>;
}
return this.props.children;
}
}
Use boundaries around meaningful areas
Do not necessarily wrap the entire application in one boundary. A dashboard, report viewer, or payment widget can have its own boundary so one broken area does not destroy unrelated UI.
<ErrorBoundary>
<ReportsPage />
</ErrorBoundary>
<ErrorBoundary>
<PaymentWidget />
</ErrorBoundary>
What it does not catch
- Event-handler errors in the same way as render errors.
- Asynchronous errors from arbitrary promises.
- Server-side rendering errors in the same manner.
- Errors thrown by the boundary itself.
Expected output
Reports failed to load.
Something went wrong in
the Reports section.
[Try Again] [Go to Dashboard]
Logging
The boundary should report useful information to an observability platform in production. Do not display stack traces or sensitive information to end users.
Common mistakes
- Using an Error Boundary as a replacement for API error handling.
- Showing technical stack traces to users.
- Having one boundary around the entire application only.
- Failing to provide a recovery action.
Interview questions
- What is an Error Boundary?
- Can a functional component itself implement the traditional class Error Boundary API?
- What errors does it catch?
- How would you design fallback UI?