Frontend System Design · Lesson 53 of 86 · 4 min
Global Error Boundaries in React
This topic separates candidates who build features from those who build resilient applications. Your answer shows if you think about production stability.
How to Prevent a Single Component from Crashing Your App
An uncaught JavaScript error during a React render will unmount the entire component tree. The user sees a blank screen. This is a critical failure.
Error Boundaries are React's solution. They are class components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of crashing.
An Error Boundary must be a class component. It works by defining one or both of these lifecycle methods:
static getDerivedStateFromError(error): Runs first, after a child component throws. Its only job is to return a state object (e.g.,{ hasError: true }) to trigger a re-render that shows your fallback UI.componentDidCatch(error, errorInfo): Runs aftergetDerivedStateFromError. Use this for side effects, like logging the error and component stack (errorInfo) to an external service.
Here is a complete, production-ready Error Boundary. You should be able to write this from memory.
import React, { Component, ErrorInfo, ReactNode } from "react";
interface Props {
children: ReactNode;
fallback: ReactNode;
}
interface State {
hasError: boolean;
}
class ErrorBoundary extends Component<Props, State> {
public state: State = {
hasError: false,
};
public static getDerivedStateFromError(_: Error): State {
// Update state so the next render will show the fallback UI.
return { hasError: true };
}
public componentDidCatch(error: Error, errorInfo: ErrorInfo) {
// You can log the error to an error reporting service here.
// We'll cover this in the next lesson.
console.error("Uncaught error:", error, errorInfo);
}
public render() {
if (this.state.hasError) {
return this.props.fallback;
}
return this.props.children;
}
}
export default ErrorBoundary;
What Error Boundaries Don't Catch
This is the most common follow-up question in an interview. Knowing the limitations is as important as knowing the implementation.
Error Boundaries only catch errors that happen during React's "render phase": rendering, lifecycle methods, and constructors. They do not catch errors inside:
- Event handlers (like
onClickoronChange) - Asynchronous code (
setTimeout,requestAnimationFramecallbacks, promises) - Server-Side Rendering (SSR)
- The Error Boundary component itself
The interview question: "I put an Error Boundary around my component, but when I click a button that throws an error, the app still crashes. Why?"
Your answer: "Error Boundaries don't catch errors in event handlers. Those errors don't happen during a render lifecycle. You need to use a standard
try/catchblock inside the event handler itself to manage them."
For async code, use .catch() on your promises or async/await with try/catch.
Where to Place Your Boundaries
Strategic placement is key. You have a spectrum of choices, each with a trade-off.
At one end, a single "global" boundary high in your component tree. This is a good safety net for unexpected, application-breaking errors.
At the other end, granular boundaries around individual widgets or features. For example, wrap a third-party charting library, a complex form, or a single panel on a dashboard. If that one part fails, the rest of the page remains fully interactive.
Most mature applications use a hybrid approach:
- A "global" boundary wraps the main application layout or router view. This shows a generic "Something went wrong, please refresh" page.
- Specific boundaries wrap independent, non-critical parts of the UI. These can show a more contextual fallback, like "This widget could not be loaded."
The trap: Don't wrap your entire application in index.js. If your top-level boundary catches an error, the user sees a fallback UI but might lose access to a global navigation bar or a support chat widget that should always be available. A better "global" boundary lives inside your root App component, wrapping only the dynamic content area.
This flow shows what happens when a boundary is triggered.
Designing a Good Fallback and Recovery Experience
Simply showing a fallback UI is not enough. A good system allows for recovery and provides useful information for debugging.
Your fallback UI should not be a dead end. At a minimum, include a button to refresh the page. This is a simple but effective way for users to resolve transient issues.
For more complex scenarios, you can build a recovery mechanism. Pass a reset function to your ErrorBoundary that can be called from the fallback component. This function would reset the boundary's state (this.setState({ hasError: false })) and potentially clear any application state that led to the crash. This allows the user to "try again" without a full page reload.
Remember componentDidCatch gives you errorInfo, which contains the componentStack. This is a trace of which component threw the error. It's invaluable. Always log both the error and the full errorInfo object to your reporting service. This is the bridge between a user reporting "it broke" and you knowing exactly where to look.
Try it
Implement an ErrorBoundary component. Use it to wrap a simple component that has a button. Make the button's onClick handler set a state variable that causes the component to throw an error on its next render (e.g., if (this.state.shouldCrash) { throw new Error('Crashed!'); }). Verify that your fallback UI appears.
Next: We'll send the errors caught here to a real monitoring service in Error Reporting: Sentry and LogRocket.
Lock it in — apply this lesson under interview conditions.