Error Boundary is a component-circuit breaker that catches errors in child components and shows a fallback interface instead of crashing the entire application.
Simple analogy: Imagine a building has fire extinguishers (Error Boundaries). If a fire (error) starts in one room (component), the extinguisher puts it out in that room, and the rest of the building continues to work. Without extinguishers, the whole house would burn down.
What Error Boundary looks like (class component only):
1class ErrorBoundary extends React.Component {2 state = { hasError: false, error: null };34 static getDerivedStateFromError(error) {5 return { hasError: true, error };6 }78 componentDidCatch(error, info) {9 console.error('Caught error:', error, info);10 }1112 render() {13 if (this.state.hasError) {14 return <h1>Something went wrong: {this.state.error.message}</h1>;15 }16 return this.props.children;17 }18}1920// Usage21<ErrorBoundary>22 <Profile userId={id} /> {/* If it crashes — the rest works */}23</ErrorBoundary>
What Error Boundary does NOT catch:
For functional components there is no componentDidCatch hook yet. Use the react-error-boundary library.
Production configuration example:
1import { ErrorBoundary } from "react-error-boundary";23function ErrorFallback({ error, resetErrorBoundary }) {4 return (5 <div role="alert">6 <h2>Something went wrong</h2>7 <pre>{error.message}</pre>8 <button onClick={resetErrorBoundary}>Try again</button>9 </div>10 );11}1213function App() {14 return (15 <ErrorBoundary16 FallbackRender={ErrorFallback}17 onReset={() => window.location.reload()}18 >19 <Router />20 </ErrorBoundary>21 );22}
Monitoring/observability: Log errors to a service like Sentry or LogRocket. Include component stack traces (provided by componentDidCatch second argument) to pinpoint exactly where the error occurred in the component tree.