React - Error Boundaries
Overview
Estimated time: 20–30 minutes
Error boundaries catch JavaScript errors anywhere in their child component tree, log them, and display a fallback UI.
Learning Objectives
- Understand what error boundaries can and cannot catch.
- Implement a simple error boundary and use a fallback UI.
Prerequisites
- Components & State
Try it: Error Boundary
View source
class ErrorBoundary extends React.Component {
constructor(props){ super(props); this.state = { hasError: false }; }
static getDerivedStateFromError(err){ return { hasError: true }; }
componentDidCatch(err, info){ console.error('Caught by boundary', err, info); }
render(){ return this.state.hasError ? this.props.fallback : this.props.children; }
}
function Boom(){ throw new Error('Boom!'); }
function App(){
return (
<ErrorBoundary fallback={<p>Something went wrong.</p>}>
<Boom />
</ErrorBoundary>
);
}
ReactDOM.createRoot(document.getElementById('try-eb')).render(<App />);
Syntax primer
getDerivedStateFromError
andcomponentDidCatch
are class lifecycle methods used by error boundaries.- Functional components cannot be error boundaries (as of React 18).
Common pitfalls
- Error boundaries do not catch errors in event handlers (handle those manually).
- They catch render, lifecycle, and constructor errors of their children.
Exercises
- Wrap only part of the tree and provoke an error there to see local fallback.
- Log errors to a server in
componentDidCatch
.
Checks for Understanding
- What kinds of errors do error boundaries catch, and which do they not?
- Where should you place error boundaries in an app?
Show answers
- They catch render, lifecycle, and constructor errors in their descendants; they don’t catch event handler errors.
- Around risky subtrees (e.g., widgets, routes) to isolate failures and show localized fallbacks.