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.
Component Tree Builder
Visual Tree
Error Boundary Code
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.
Related Products
on GumroadDevPlaybook Interview Vault
210+ real technical interview questions with model answers, asked at Google, Meta, Amazon, Microsoft, Stripe, and Shopify. Covers Frontend (55), Backend (55), System Design (50), and DSA (50). Available in English and Traditional Chinese.
Buy on Gumroad →TypeScript Quick Reference Toolkit
5 practical reference files for TypeScript developers: cheatsheet, TS vs JS comparison, 20 utility types with real examples, tsconfig best practices template, and 15 common mistakes guide. Print it. Keep it on your desk.
Buy on Gumroad →AI Prompt Engineering Toolkit
58 structured prompt templates for Claude, ChatGPT, and Gemini — organized by use case. Code Review, Debugging, Documentation, Architecture, and 10 model-specific tips. Stop writing prompts from scratch.
Buy on Gumroad →You Might Also Need
SQL to TypeScript Types
Convert SQL CREATE TABLE statements to TypeScript interfaces and Zod schemas. Maps SQL column types to TypeScript with nullability.
Open free tool →
TanStack Query Config Builder
Configure TanStack Query (React Query v5) staleTime and gcTime visually. Generate QueryClient config and useQuery/useMutation TypeScript code with retry logic.
Open free tool →
TypeScript Discriminated Union Builder
Build TypeScript discriminated unions visually. Add variants with fields and get type-safe switch statements, type guards, and exhaustive checking code.
Open free tool →
More Free Tools
Related Articles
React 19: Complete Guide to New Features in 2026
Everything new in React 19: use() hook, Actions, optimistic updates, ref as prop, form actions, and the React Compiler. Production-ready patterns with TypeScript examples.
SolidJS vs React 2026: Performance, DX, and When to Choose Each
Deep comparison of SolidJS and React in 2026: fine-grained reactivity vs virtual DOM, signals vs useState, performance benchmarks, SolidStart vs Next.js, and honest real-world tradeoffs.
Frontend Interview Questions 2026: React, TypeScript & More
The most common frontend interview questions in 2026 with detailed answers covering React, TypeScript, performance, accessibility, and system design.
Building Type-Safe APIs with tRPC and Zod in 2026
Complete tRPC + Zod tutorial: set up end-to-end type-safe APIs with zero code generation. Includes routers, middleware, input validation, error handling, and React Query integration.
TypeScript Best Practices 2025: Type Safety Patterns Every Developer Should Know
Master TypeScript type safety patterns in 2025. Branded types, discriminated unions, conditional types, template literals, and type guards with practical code examples.
Enjoying this tool? Get more like it.
Weekly developer tool guides, productivity playbooks & AI tricks. Free. No spam.
Unlock AI-Powered Dev Tools
- ⚡ AI Code Review, Doc Generator & SQL Builder
- ⚡ All premium templates & early access
- ⚡ Member discounts on Gumroad products
$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.
MIT licensed · Instant download · No subscription
See what's included → Browse all deals →