Hello! Welcome to our next lesson on building robust React applications.
In the last lesson, we focused on testing the "happy path" by simulating user interactions with @testing-library/user-event. We learned how to write tests that give us confidence that our components work as expected when users click, type, and navigate.
Today, we're shifting our focus to the "unhappy path." What happens when something unexpectedly goes wrong during rendering? This lesson will teach you how to implement Error Boundaries using a class component to catch and handle runtime errors gracefully. This is a critical skill for building resilient, production-ready applications that don't just crash and show a blank screen to your users.
1. The Problem: Why Uncaught Errors Are So Destructive in React
In a typical JavaScript application, an error in one part of the UI might break that specific feature, but the rest of the page often remains functional. React, however, behaves differently. Since React 16, an uncaught JavaScript error in any component during the rendering phase doesn't just break that component—it corrupts React's internal state and causes it to unmount the entire application tree.
The result? Your user sees a blank white screen.

Your first instinct, given your programming experience, might be to use a standard try...catch block. However, due to React's declarative nature, this approach has significant limitations.
How to handle errors in React: full guide
The article 'How to handle errors in React' by Nadia Makarevich provides an excellent deep-dive into why traditional try...catch blocks fall short. It explains the technical reasons related to React's render cycle and component elements.
Please read the sections 'Why we should catch errors in React' and 'Simple try/catch in React: how to and caveats'. Focus on understanding the three limitations explained: issues with useEffect, errors in child components, and the prohibition of state updates during render.
As the article explains, try...catch cannot reliably catch errors from child components or from asynchronous hook logic because the code that throws the error is executed by React after the try...catch block in the parent component has already completed.
2. The Solution: Implementing an Error Boundary
To solve this problem, React introduced the concept of an Error Boundary. An Error Boundary is a special React component that catches JavaScript errors anywhere in its child component tree, logs those errors, and displays a fallback UI instead of the component tree that crashed.
It acts like a try...catch block, but for React components.

There are two fundamental rules for creating an Error Boundary:
- It must be a class component. This is one of the very few use cases where class components are still necessary in modern React, as there is currently no hook equivalent for this functionality.
- It must define at least one (or both) of these lifecycle methods:
static getDerivedStateFromError()componentDidCatch()
Let's see how to build one.
Error Boundary // The React Try Catch
This video from the channel 'basarat' provides a concise, TypeScript-focused walkthrough of building an Error Boundary. It clearly distinguishes between the two lifecycle methods and their purposes.
Watch from the beginning to 03:29 to see why try/catch fails for render errors. Then, watch from 03:29 to 05:51 to see the creation of a basic Error Boundary class component. Finally, skip to 07:55 and watch until 09:12 to understand the role of componentDidCatch for logging.
3. Building a Fully-Typed Error Boundary in TypeScript
Let's formalize what we saw in the video and build a robust, reusable Error Boundary with proper TypeScript types. We'll examine a complete implementation.
Error Boundaries - React with TypeScript
The 'Error Boundaries - React with TypeScript' article by Steve Kinney provides an excellent, production-quality example of a typed Error Boundary. We will use this as our primary code reference.
Carefully study the code block in the 'Basic Error Boundary Implementation' section. Pay close attention to the interfaces for props (ErrorBoundaryProps) and state (ErrorBoundaryState), and the implementation of the two key lifecycle methods.
Let's break down the code from that article:
Props and State Interfaces:
First, we define the component's API and internal state.
import { Component, ErrorInfo, ReactNode } from 'react';
interface ErrorBoundaryProps {
children: ReactNode; // What the boundary wraps
// We'll add more here later
}
interface ErrorBoundaryState {
hasError: boolean;
}
The Class Component:
This is the core structure. It extends React.Component and uses our defined prop and state types.
class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
// 1. Initialize state in the constructor
constructor(props: ErrorBoundaryProps) {
super(props);
this.state = { hasError: false };
}
// 2. Update state so the next render will show the fallback UI.
static getDerivedStateFromError(error: Error): ErrorBoundaryState {
return { hasError: true };
}
// 3. Log the error to an error reporting service
componentDidCatch(error: Error, errorInfo: ErrorInfo) {
// Example: logErrorToMyService(error, errorInfo);
console.error("Uncaught error:", error, errorInfo);
}
// 4. Conditionally render the children or the fallback UI
render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
Understanding the Lifecycle Methods:
static getDerivedStateFromError(): This method is invoked after an error has been thrown by a descendant component. It receives theerroras an argument and should return a value to updatestate. Its job is purely to trigger a re-render in an "error" state. You should not cause any side effects here.componentDidCatch(): This method is invoked after the error is caught andgetDerivedStateFromErrorhas run. It's called during the "commit phase," so side effects are allowed. This is the ideal place to log your error details to a service like Sentry, LogRocket, or Datadog. It receives two arguments: theerrorobject and anerrorInfoobject which contains acomponentStacktrace.
4. Strategic Placement of Error Boundaries
Where you place your Error Boundary is a strategic decision. It determines the "blast radius" of an error.
- Wrap the entire app: You can wrap your entire application just below the root. If any component throws, the user sees a generic "Something went wrong" page. This is a good safety net, but not a great user experience.
- Wrap routes: A common pattern is to wrap each page or route. An error on the settings page will show a fallback for that page, but the user can still navigate to their dashboard.
- Wrap individual widgets: For complex, independent parts of the UI like a sidebar, a complex chart, or a third-party widget, you can wrap them individually. An error in one widget won't bring down the rest of the page.
Example Usage:
import ErrorBoundary from './ErrorBoundary';
import UserProfile from './UserProfile';
import UserActivityFeed from './UserActivityFeed';
function Dashboard() {
return (
<div>
<h1>My Dashboard</h1>
<ErrorBoundary>
<UserProfile />
</ErrorBoundary>
<ErrorBoundary>
<UserActivityFeed />
</ErrorBoundary>
</div>
);
}
In this example, if UserProfile crashes, its fallback UI will be shown, but UserActivityFeed will continue to render normally.
Test your understanding!
Imagine you are building a social media dashboard. It has three main sections: a Header with navigation, a Timeline component that shows posts, and a TrendingTopics sidebar. The Timeline component is complex and occasionally fails due to malformed data. The TrendingTopics is stable, and the Header must always remain visible.
Where would you place your Error Boundary/Boundaries to achieve the best user experience?
Show answer
The best approach would be to wrap only the Timeline component with an Error Boundary:
function SocialDashboard() {
return (
<div>
<Header />
<main>
<ErrorBoundary fallback={<div>The timeline could not be loaded. Please try again later.</div>}>
<Timeline />
</ErrorBoundary>
<TrendingTopics />
</main>
</div>
);
}
This ensures that if the Timeline crashes, the user sees a helpful fallback message in its place, but the Header and TrendingTopics sidebar remain fully functional. The user can still navigate away or interact with other parts of the page. Wrapping the entire <main> section would be acceptable, but less ideal as it would also hide the stable TrendingTopics component.
5. Advanced Pattern: A Resettable Error Boundary
A great user experience doesn't just show an error; it gives the user a way to recover. Let's enhance our Error Boundary to include a "Try Again" button. This is a very common and powerful pattern in production applications.
To do this, we need to:
- Add a
resetmethod to our class component that setshasErrorback tofalse. - Pass this
resetmethod down to a customizable fallback component.
Error Boundaries - React with TypeScript
The same article from Steve Kinney demonstrates this advanced pattern perfectly. It shows how to add a reset function and pass it down to a specialized fallback component.
Study the code under the 'Enhanced Error Boundary with Reset Capability' section. Notice how resetErrorBoundary is defined as an instance method and how it's passed as a prop to the FallbackComponent. This is a powerful composition pattern.
The key piece of logic is the resetErrorBoundary method:
class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
// ... constructor, getDerivedStateFromError, componentDidCatch
resetErrorBoundary = () => {
this.setState({ hasError: false, error: undefined });
};
render() {
const { hasError, error } = this.state;
const { fallback: FallbackComponent, children } = this.props;
if (hasError && error) {
return (
<FallbackComponent
error={error}
resetErrorBoundary={this.resetErrorBoundary}
/>
);
}
return children;
}
}
This pattern separates the error-catching logic of the boundary from the error-displaying logic of the fallback UI, making both more reusable.
Conclusion
You have now learned one of the most important patterns for building resilient React applications. While functional components and hooks dominate modern React, the class-based Error Boundary remains an essential tool in your developer toolkit. By catching runtime rendering errors, you prevent catastrophic crashes and provide a much better user experience.
Key Takeaways:
- Uncaught render-phase errors in React crash the entire application.
- Error Boundaries are class components that catch these errors in their children.
- Use
static getDerivedStateFromErrorto update state and render a fallback UI. This method must be pure. - Use
componentDidCatchto perform side effects, such as logging the error to an external service. - The placement of Error Boundaries is a strategic decision that contains the "blast radius" of an error.
- Advanced Error Boundaries can be made reusable and include reset functionality to allow users to recover from transient errors.
Preview of the Next Lesson:
In our next lesson, we will continue our journey into application optimization by looking at code splitting with React.lazy and <Suspense>. This technique allows you to improve your app's initial load time by only loading the code for the components that are currently needed, which pairs nicely with the error and loading states we've been discussing.