DEV Community

Cover image for React Error Boundaries
Evan Hameed
Evan Hameed

Posted on

React Error Boundaries

This article explains how to use React error boundaries to catch errors and shows an abstract error page to inform users that something is not working properly on the website.

How does React handle errors in nature?

When javascript errors occur during rendering, React can not really know how to resolve and recover from them. There is no generic blueprint for React to understand the errors that happen in rendering. It also can not revert back to a stable version before the error occurs. As a result, React unmount all the components as a last resort. That is the reason why when such errors occur, the page goes completely blank as demonstrated below:

Considering this error in this component:

import React from 'react'

const Home: React.FC = () => {
  throw new Error('Error happend!');
  return (
    <div>Home</div>
  )
}

export default Home
Enter fullscreen mode Exit fullscreen mode

The result of that error would look something like this:

Error not handled

The whole components tree got unmounted, this might look very controversial to end-users. They might think that they should wait or that there is something wrong on their end.

Not all users can inspect web pages and find out what is wrong with web applications. Therefore React provides Error Boundaries.

React Error Boundaries

Error boundaries are React components that handle javascript errors anywhere in the components tree by logging them and providing a custom fallback UI to inform users that there is something wrong in the application.

Error Boundaries help in catching errors and prevent unmounting not related components.

Using error boundaries in React application

  • Create a component, and add the following inside it.
import React from "react";
import ErrorPage from "../components/Error";


interface IErrorBoundryState {
    hasError: boolean;
}
interface IErrorBoundryProps {
    children: React.ReactNode;
}


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

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

    componentDidCatch(error: Error, info: any) {
        console.log('Error in component did Catch', error);
        console.log('any info', info);
    }
    render() {
        if (this.state.hasError) {
            return <ErrorPage />; // Fallback Customizable component 
        }
        return this.props.children;
    }
}


export default ErrorBoundary;
Enter fullscreen mode Exit fullscreen mode
  • All what is left now is to wrap the components we want to catch errors from with the above component. We can wrap specific components, or we can be more generic and wrap the main entry.
import ErrorBoundary from './helpers/ErrorBoundry';

root.render(
  <React.StrictMode>
    <ErrorBoundary>
      <App />
    </ErrorBoundary>
  </React.StrictMode>
);
Enter fullscreen mode Exit fullscreen mode

Now the previous error that we had earlier will be catched with the help of this error boundary as demonstrated in the following:

Something went wrong page

Conclusion

Error boundaries are very important concepts to handle errors and prevent crashing and unmounting the whole components when any error occurs in web applications. They are also a good way to tell end-users about errors instead of showing blank pages.

Read more about error boundaries in the official docs of React.

Top comments (0)