The JavaScript Error Handling lesson's try/catch doesn't catch errors thrown during rendering inside a component — by default, an error there crashes the entire React app, showing a blank page. An error boundary is React's tool for containing that damage to one part of the tree instead.
An error boundary is a component that catches JavaScript errors thrown by its children during rendering, logs them, and displays a fallback UI instead of the crashed tree. As of the current version of React, this specifically requires a class component — the one place in modern React you'll still write one, since no hook-based equivalent exists yet:
import { Component } from 'react';
class ErrorBoundary extends Component {
state = { hasError: false };
static getDerivedStateFromError() {
return { hasError: true };
}
componentDidCatch(error, info) {
console.error('Caught by ErrorBoundary:', error, info);
}
render() {
if (this.state.hasError) {
return <h2>Something went wrong.</h2>;
}
return this.props.children;
}
}Wrap it around whatever part of the tree should fail independently — composed with children, exactly like the Component Composition lesson:
function App() {
return (
<div>
<Header /> {/* stays up even if the widget below crashes */}
<ErrorBoundary>
<UnstableWidget />
</ErrorBoundary>
<Footer />
</div>
);
}| Doesn't catch | Handle it with |
|---|---|
| Errors inside event handlers | A regular try/catch inside the handler itself |
| Errors inside a fetch() call | The .catch() / try-catch pattern from the Fetching Data lesson |
| Errors during server-side rendering | Framework-specific error handling (outside the scope of this section) |
An error boundary is specifically for the case those other tools don't cover: something going wrong while a component is actually rendering.
A few boundaries, placed deliberately
A handful of well-placed error boundaries — around a page's major independent sections — usually beats wrapping every single small component individually. The goal is containing a crash to the section that broke, not eliminating every possible failure.