ReactJS Foundations

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.

Download the examples, report issues, and ask/answer questions in the discussion area by visiting the book's github page. All of the code for the book is also available on codesandbox.io for you to play around with.

ReactJS Foundations is published by John Wiley and Sons, Inc and is available in paperback and eBook.

React JS Foundations

Latest Blog Posts

React Router v6 Code Posted

Chapter 12 covers how to do Routing in React using React Router v5. In the time since the book came out, React Router v6 has been released, which includes some changes to how it’s used. I’m also working on writing a version of Chapter 12 that covers React Router 6. I’ll post that to the […]

Read More >

Errata: Chapter 6

The final code example in the Shallow Copies and the Spread Operator section on page 160 shows a rest parameter with only two periods. There should be three. The correct code is:

Read More >

React 18 Update

The biggest change in React 18 is the addition of concurrent rendering. With concurrent rendering, you can mark state updates as non-urgent in order to improve the performance of your user interface. Concurrent rendering is opt-in. What this means is that it’s only enabled when you use a concurrent feature. As a result, apps built […]

Read More >