DEV Community

Aman Kureshi
Aman Kureshi

Posted on

πŸ›‘ Error Boundaries in React β€” Catch JavaScript Errors Without Crashing the Whole App

πŸ›‘ Error Boundaries in React β€” Catch JavaScript Errors Without Crashing the Whole App

Error boundaries are React components that catch JavaScript errors in child components, log them, and show a fallback UI instead of crashing the entire app.

🎯 Why use error boundaries?
β€’ Prevent UI from breaking due to unexpected errors
β€’ Provide a graceful fallback (like an error message)
β€’ Great for critical areas like routes, forms, dashboards

⚠️ Only class components can be error boundaries (as of now).

🧱 Example:

class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(error) {
    return { hasError: true };
  }

  componentDidCatch(error, info) {
    console.error("Error caught:", error, info);
  }

  render() {
    if (this.state.hasError) {
      return <h2>Something went wrong.</h2>;
    }
    return this.props.children;
  }
}
Enter fullscreen mode Exit fullscreen mode

βœ… Usage:

<ErrorBoundary>
  <MyComponent />
</ErrorBoundary>
Enter fullscreen mode Exit fullscreen mode

πŸ“Œ Key points:
β€’ Catches errors during rendering, lifecycle, and constructors
β€’ Does not catch event handler errors (handle them manually)
β€’ Useful for isolating risky parts of the app

Error boundaries improve the resilience of your React app and ensure a better user experience even when something fails.

Top comments (0)