Back to Pathway
patternsadvanced

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 Simulation

Simulation Engine Idle
Click "Execute Code" to run state reconciliation simulation.

Executable Code Snippet

Component.jsx
JSX / React 19
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}
Technical Takeaways & Best Practices
  • 01.Component re-renders are triggered by state or prop changes.
  • 02.Reconciliation algorithm diffs the Virtual DOM to minimize actual DOM updates.
  • 03.Automatic batching optimizes multiple state updates into a single render cycle.

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

App Root (Safe)
Crashed Widget (Caught)
Sidebar (Safe)

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."