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 →

Published by Bramus!

Bramus is a frontend web developer from Belgium, working as a Chrome Developer Relations Engineer at Google. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Join the Conversation

2 Comments

Leave a comment

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.