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)