Error boundaries catch errors in React component tree, while try-catch handles imperative code.
Error boundary:
1import { Component, ErrorInfo, ReactNode } from "react";23interface Props {4 children: ReactNode;5 fallback?: ReactNode;6}78interface State {9 hasError: boolean;10 error: Error | null;11}1213class ErrorBoundary extends Component<Props, State> {14 state: State = { hasError: false, error: null };1516 static getDerivedStateFromError(error: Error): State {17 return { hasError: true, error };18 }1920 componentDidCatch(error: Error, info: ErrorInfo) {21 logErrorToService(error, info.componentStack);22 }2324 render() {25 if (this.state.hasError) {26 return this.props.fallback || <h1>Something went wrong</h1>;27 }28 return this.props.children;29 }30}3132// Usage33<ErrorBoundary fallback={<ErrorPage />}>34 <BuggyComponent />35</ErrorBoundary>
Key differences: | Feature | Error Boundary | try-catch | |---------|----------------|----------| | Handles | Render errors | Imperative code | | Scope | Component tree | Code block | | Recovery | Shows fallback UI | Must handle manually | | Works with | Async, hooks, lifecycle | Synchronous code |
What error boundaries catch:
What they DON'T catch:
Best practices: