Error Boundaries
Error boundaries are components that catch JavaScript errors anywhere in their child component tree and display a fallback UI.
Mental Model
"The Circuit Breaker: When a toaster short-circuits in the kitchen, the breaker trips to protect the entire house from losing power."
Interactive Engine Walkthrough
Reference Code Snippet
1class ErrorBoundary extends React.Component {
2 state = { hasError: false };
3
4 static getDerivedStateFromError(error) {
5 return { hasError: true };
6 }
7
8 render() {
9 if (this.state.hasError) return <h1>Something went wrong.</h1>;
10 return this.props.children;
11 }
12}- 01.Error boundaries catch errors during rendering, lifecycle methods, and constructors of child trees.
- 02.They do NOT catch errors inside async callbacks (fetch/setTimeout) or event handlers (use try/catch there).
- 03.Wrap discrete features (e.g. sidebar, feed, chat) in separate boundaries so one failure does not crash the entire app.
01. Circuit Breakers
In vanilla JS, a crash in one part of the code can stop the whole script. In React, Error Boundaries ensure that a crash in one component doesn't unmount the entire app. It "catches" the error and allows you to display a fallback UI (like a "Sorry" message).
Containment Map
02. Limitations
Error Boundaries only catch errors during **Rendering**, in **Lifecycle methods**, and in **Constructors**. They **cannot** catch errors in event handlers, asynchronous code (like `fetch`), or server-side rendering. For those, you still need standard `try/catch` blocks.
Architectural Advice
"Granularity is key. Don't just wrap your whole app in one boundary. Wrap major UI blocks (Sidebar, Feed, Profile) in their own boundaries so that if the Feed crashes, the user can still navigate using the Sidebar."