Skip to main content

React Error Boundary Simulator

Build a component tree, mark which component throws, and visualize which error boundary catches the error. Includes class and hook-based boundary code.

✓ Visual tree propagation ✓ Class & hook boundary code ✓ Error logging snippet

Component Tree Builder

Components

Visual Tree

Normal Error Boundary Throws / Caught Unmounted

Error Boundary Code

typescript
import React, { Component, ErrorInfo, ReactNode } from 'react';

interface Props {
  children: ReactNode;
  fallback?: ReactNode;
  onError?: (error: Error, errorInfo: ErrorInfo) => void;
}

interface State {
  hasError: boolean;
  error: Error | null;
}

class ErrorBoundary extends Component<Props, State> {
  constructor(props: Props) {
    super(props);
    this.state = { hasError: false, error: null };
  }

  static getDerivedStateFromError(error: Error): State {
    // Called during render phase — update state to show fallback UI
    return { hasError: true, error };
  }

  componentDidCatch(error: Error, errorInfo: ErrorInfo): void {
    // Called after render — use for logging
    this.props.onError?.(error, errorInfo);
    console.error('ErrorBoundary caught:', error, errorInfo.componentStack);
  }

  render() {
    if (this.state.hasError) {
      return this.props.fallback ?? (
        <div role="alert" className="error-fallback">
          <h2>Something went wrong</h2>
          <button onClick={() => this.setState({ hasError: false, error: null })}>
            Try again
          </button>
        </div>
      );
    }
    return this.props.children;
  }
}

// Usage:
// <ErrorBoundary fallback={<p>Failed to load</p>}>
//   <MyWidget />
// </ErrorBoundary>

export default ErrorBoundary;

Frequently Asked Questions

What is an error boundary in React?▼

An error boundary is a React component that catches JavaScript errors in its child component tree, logs them, and displays a fallback UI instead of crashing the entire app. Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of child components — but NOT in event handlers, async code, or server-side rendering.

Why can't I use hooks to create error boundaries?▼

React error boundaries must be class components because they use the getDerivedStateFromError and componentDidCatch lifecycle methods, which have no hook equivalents. The React team is working on a future hook-based API (useErrorBoundary exists in some libraries), but as of React 18, class components are required for defining boundaries. You can use the 'react-error-boundary' library as a wrapper.

What is the react-error-boundary library?▼

react-error-boundary is a lightweight utility that wraps React's class-based error boundary API in a user-friendly component and hook interface. It provides ErrorBoundary component, useErrorBoundary hook for triggering boundaries from async code or event handlers, and withErrorBoundary HOC. It's the de facto standard for error handling in modern React apps.

How do error boundaries propagate upward?▼

When a component throws, React walks up the component tree looking for the nearest ancestor that is an error boundary. If found, that boundary catches the error and renders its fallback. If no boundary is found, the entire React tree unmounts and the error propagates to the browser. This is why it's good practice to place boundaries at multiple levels.

Should I put an error boundary around every component?▼

No — that would be excessive and hide real bugs. Best practice: (1) one top-level boundary as a safety net, (2) boundaries around major UI regions (sidebar, main content, widgets) so one failure doesn't kill the whole UI, (3) boundaries around third-party components you don't control, (4) boundaries around data-fetching components. Don't wrap every leaf component.

Share this tool: X / Twitter LinkedIn
✓ 60,000+ developers use DevPlaybook ★★★★★ 4.8 / 5 on Gumroad ✓ MIT licensed · Instant download ✓ No login required

Related Products

on Gumroad

You Might Also Need

More Free Tools

Enjoying this tool? Get more like it.

Weekly developer tool guides, productivity playbooks & AI tricks. Free. No spam.

DevPlaybook Pro 7 days free

Unlock AI-Powered Dev Tools

  • ⚡ AI Code Review, Doc Generator & SQL Builder
  • ⚡ All premium templates & early access
  • ⚡ Member discounts on Gumroad products
Start Free Trial →

$9/mo after trial · Cancel anytime

Want the full toolkit?

Get DevPlaybook Pro

Every template, guide, boilerplate, and automation script in one bundle. 13 premium products — grab them all at once and save big.

$79
$241 separately Save $162 (67% off)
Get DevPlaybook Pro — $79 →

MIT licensed · Instant download · No subscription

See what's included → Browse all deals →