Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Error Boundaries in React

Introduction

Error boundaries are a powerful feature in React that allow you to catch JavaScript errors in your component tree, log those errors, and display a fallback UI instead of crashing the whole application. They provide a way to gracefully handle errors without losing the entire application state.

What are Error Boundaries?

An error boundary is a React component that implements either static getDerivedStateFromError() or componentDidCatch() lifecycle methods. These methods allow the component to catch errors occurring in its child component tree and update the UI accordingly.

Note: Error boundaries only catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.

How to Use Error Boundaries

To create an error boundary, you can define a class component as shown below:


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

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

    componentDidCatch(error, errorInfo) {
        // 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; 
    }
}
                

To use this error boundary, simply wrap your components like this:



    <MyComponent />

                

Best Practices

  • Use error boundaries at specific points in your component hierarchy to isolate errors effectively.
  • Log errors using a service like Sentry or LogRocket for better debugging.
  • Provide user-friendly fallback UIs to enhance user experience.
  • Do not use error boundaries to catch errors in event handlers or asynchronous code.

FAQ

Can error boundaries catch errors in async code?

No, error boundaries cannot catch errors that occur in asynchronous code such as setTimeout or Promises.

Can error boundaries catch errors in event handlers?

No, errors in event handlers cannot be caught by error boundaries. You must handle those errors manually.

Can you use error boundaries with functional components?

Yes, you can use error boundaries with functional components, but they must be wrapped in a class component that implements the error boundary methods.