DEV Community

Cover image for Error Boundary in React js
Ashwani Singh
Ashwani Singh

Posted on

Error Boundary in React js

In React, an Error Boundary is a component that helps catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of crashing the entire application. This feature is particularly useful for improving the user experience by gracefully handling unexpected errors.

Key Concepts of Error Boundaries

1. Definition and Use:

Error boundaries are React components that catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.

They do not catch errors for:

  • Event handlers (use try-catch in the event handler).
  • Asynchronous code (e.g., setTimeout or requestAnimationFrame callbacks).
  • Server-side rendering.
  • Errors thrown in the error boundary itself (e.g., inside componentDidCatch).

2. How to Create an Error Boundary:

An error boundary is any React component that implements either componentDidCatch lifecycle method or the static getDerivedStateFromError method.

import React from 'react';

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

  static getDerivedStateFromError(error) {
    // Update state so the next render will show the fallback UI.
    return { hasError: true };
  }

  componentDidCatch(error, errorInfo) {
    // You can also log the error to an error reporting service
    console.error("Error caught by ErrorBoundary:", error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      // You can render any custom fallback UI
      return <h1>Something went wrong.</h1>;
    }

    return this.props.children; 
  }
}
Enter fullscreen mode Exit fullscreen mode

3. Using an Error Boundary:

<ErrorBoundary>
  <AppComponet />
</ErrorBoundary>

Enter fullscreen mode Exit fullscreen mode

Best Practices

1. Granularity:

It's better to place error boundaries at the top level of your application to catch all errors, but you can also place them around specific components to isolate errors within specific parts of your app.

2. Logging:

Implement logging in componentDidCatch to send error details to an error monitoring service (e.g., Sentry, LogRocket).

3. Fallback UI:

Make sure the fallback UI is user-friendly and provides a way to recover from the error if possible (like a "Try Again" button).

Limitations.

1. Event Handlers:

Error boundaries do not catch errors inside event handlers. You need to handle those manually using try-catch blocks.

2. Async Code:

Errors in asynchronous code should be handled within the async functions using try-catch blocks.

Example in Functional Components

With the introduction of hooks, you might wonder about using error boundaries in functional components. As of now, React does not provide hooks for error boundaries. You must use class components for creating error boundaries.

In summary, React's Error Boundaries are a robust way to handle errors gracefully in your application, ensuring that users have a smooth experience even when something goes wrong.

Top comments (0)