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)