What is Error Boundary in React: Explanation and Example
error boundary in React is a component that catches JavaScript errors anywhere in its child component tree and displays a fallback UI instead of crashing the whole app. It helps keep the app running smoothly by handling errors gracefully.How It Works
Think of an error boundary like a safety net under a tightrope walker. If the walker (your app's components) slips and falls (throws an error), the net catches them so they don't hit the ground hard (crash the entire app). In React, error boundaries catch errors during rendering, lifecycle methods, and constructors of their child components.
When an error happens inside a component wrapped by an error boundary, React stops rendering that part and shows a fallback UI instead. This prevents the whole app from breaking and lets you show a friendly message or alternative content to users.
Example
This example shows a simple error boundary component that catches errors and displays a message instead of crashing the app.
import React, { Component } from 'react'; class ErrorBoundary extends Component { constructor(props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError(error) { return { hasError: true }; } componentDidCatch(error, errorInfo) { console.error('Error caught by ErrorBoundary:', error, errorInfo); } render() { if (this.state.hasError) { return <h2>Something went wrong.</h2>; } return this.props.children; } } function BuggyComponent() { throw new Error('I crashed!'); // return <div>This will not render.</div>; } export default function App() { return ( <ErrorBoundary> <BuggyComponent /> </ErrorBoundary> ); }
When to Use
Use error boundaries to catch errors in parts of your app where you want to prevent the entire UI from crashing. For example, wrap error boundaries around large sections like dashboards, forms, or third-party widgets that might fail.
This helps improve user experience by showing fallback content or messages instead of a blank screen. However, error boundaries do not catch errors inside event handlers, so you still need to handle those separately.
Key Points
- Error boundaries catch errors during rendering, lifecycle methods, and constructors of child components.
- They prevent the whole React app from crashing by showing fallback UI.
- They do not catch errors inside event handlers.
- You create error boundaries by defining a class component with
getDerivedStateFromErrorandcomponentDidCatchmethods. - Use error boundaries to isolate errors in specific parts of your app for better user experience.