Writing an Error Boundary


Errors can happen in React components for many reasons. In development mode, errors will cause React to spit up a bunch of red text into the browser. This is sometimes helpful for debugging the problem.

In production mode, React will display a white screen (called the “white screen of death”) rather than report to the user what caused the error. This makes a lot of sense, but it will likely result in the user getting confused and/or leaving your app.

Error boundaries are a way to catch errors in React components before the white screen of death appears and to display something more friendly. You can even use an error boundary to provide a “try again” button and to log the error to a remote logging service.

Error boundaries are created using the getDerivedStateFromError lifecycle method and, optionally, the componentDidCatch lifecycle method. Because they depend on lifecycle methods, error boundaries must be written as class components.

The getDerivedStateFromError lifecycle method runs when a child of a component returns an error. It accepts the error as an argument and returns an object that will be used to update the state. Here’s an example of an error boundary:

import {Component} from 'react';

class ErrorBoundary extends Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false };
  }
  static getDerivedStateFromError(error) {
    return { hasError: true };
  }
  render() {
    if (this.state.hasError) {
      return <h1>There has been an error.</h1>;
    }

    return this.props.children;
  }
}

export default ErrorBoundary;

To use this error boundary, import it into a component that has a child that may return an error. Then, wrap any component with the ErrorBoundary JSX element.

import ErrorBoundary from './ErrorBoundary';

function App(props){
  return (
    <ErrorBoundary>
      <ComponentThatMightError />
    </Errorboundary>
  )
}

export default App;

If a component wrapped in the error boundary returns an error, the error boundary will catch the error and display the “There has been an error” text. If you want to give the user a chance to reset the state and try again you can also return a button that will reset the hasError state property to false, which will cause the subcomponents of the error boundary to re-render.

To learn more about error boundaries, see chapter 13 of ReactJS Foundations. You can view additional examples of Error Boundaries at reactjsfoundations.com.


Leave a Reply

Your email address will not be published.