Better Error Handling in React 16 with Error Boundaries

The first beta React 16 has been released just yesterday. Next to it running on Fiber (speeeed!), and allowing one to return Arrays in the render() method (bye bye unnecessary wrapper divs!), it also introduces the concept of Error Boundaries:

Error boundaries are React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI instead of the component tree that crashed. Error boundaries catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.

A class component becomes an error boundary if it defines a new lifecycle method called componentDidCatch(error, info)

With Error Boundaries a JavaScript error will no longer break your whole app. An example Error Boundary would be:

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

  componentDidCatch(error, info) {
    // Display fallback UI
    this.setState({ hasError: true });
    // You can also log the error to an error reporting service
    logErrorToMyService(error, info);
  }

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

Just wrap this around your own component, and it will catch any JavaScript errors inside ‘m

<ErrorBoundary>
  <MyWidget />
</ErrorBoundary>

Here’s a demo pen:

Error Handling in React 16 →

Elsewhere , ,

2 Responses to Better Error Handling in React 16 with Error Boundaries

  1. Pingback: Leveraging New Features of React 16 | Bram.us

  2. Pingback: The exciting future of React | Bram.us

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.