React 16 Error Boundaries Let You Recover Gracefully
Tags: javascript, react, webdev
Published: 2018-02-08 18:42:53

---
title: "React 16 Error Boundaries Let You Recover Gracefully"
description: "React recently announced the release of version 16 with error boundaries. They are useful so that an error in one small part of the UI doesn’t break your entire application. Instead, it’s better to contain those errors to the affected components and gracefully recover."
image: https://rollbar.com/assets/blog/images/2017-10-11-react-error-boundaries/image3.png
tags: #javascript, #react, #webdev
canonical_url: https://rollbar.com/blog/react-error-boundaries
published: true
---

React recently announced the release of version 16 with long standing feature requests including error boundaries, fragments, improved server-side rendering and more. Error boundaries are especially useful so that an error in one small part of the UI doesn’t break your entire application. Instead, it’s better to contain those errors to the affected components and recover gracefully.

You can try using error boundaries yourself in our working <strong><a href="https://codepen.io/rollbar_example/pen/JrMGQq?editors=1011" target="_blank">Codepen example</a></strong>. We forked it from Facebook's initial version to show how to add Rollbar's <strong><a href="https://rollbar.com/error-tracking/javascript/">JavaScript error logging</a></strong>. When you open this page, you can activate an error boundary by clicking at least five times on the counter. You will then see the error message “Something went wrong.” Let's dive deeper into this example to learn how error boundaries work.

![Error boundaries Codepen example](https://rollbar.com/assets/blog/images/2017-10-11-react-error-boundaries/image3.png)
<!--more-->

## What are error boundaries?

Error boundaries are React components that catch JavaScript errors anywhere in their child component tree. They can log errors and display a fallback UI to replace the component tree that has crashed. They are similar to try-catch statements in your code, but surround page elements instead.

An error boundary is a React component with a `componentDidCatch(err, info)` method. Any errors occurring in a component tree get reported up to the nearest error boundary’s `componentDidCatch` function. Note that error boundaries only catch errors in the components below them in the tree. For simple apps, you can declare an error boundary component once and use it for your whole application. For more complex applications with multiple components, you can have independent error boundaries to gracefully recover each part.

You can also report these errors to an error monitoring service like Rollbar. This will give you the ability to track how many users are affected by errors, find what caused them, and ultimately improve your user experience. We’ll show you a working example of how to do this at the end.

## How to implement React error boundaries

Here are some simple steps describing how to implement them in your code:

1. Create a component class that extends a React Component and passes the props.
2. Add a `componentDidCatch` and `render` method as shown in the below example. The `componentDidCatch` method allows you to catch the error, and change how the component is rendered. For example, you can display an error message like “Something went wrong!”

   ```js
   class ErrorBoundary extends React.Component {
     constructor(props) {
       super(props);
       this.state = { error: null, errorInfo: null };
     }

     componentDidCatch(error, errorInfo) {
       // Catch errors in any components below and re-render with error message
       this.setState({
         error: error,
         errorInfo: errorInfo      
       })
     }

     render() {
       if (this.state.errorInfo) {
         return (
           <div>Something went wrong!</div>
         );
       }
       return this.props.children;
     }
   }
   ```

3. Add your new component in HTML, surrounding the parts you would like to include in your error boundary. In this example, we are adding an error boundary around a buggy counter component.

   ```js
   <ErrorBoundary>
     <BuggyCounter/>
   </ErrorBoundary>
   ```

## Adding Rollbar to React error boundaries

For real-world production applications, it’s important to monitor errors so you understand your user’s experience. If your application is breaking, you don’t want to lose customers or have them complain on app reviews or social media. It’s much better to monitor those production errors so that you’re the first to know, and can fix the issue before more customers are impacted.

Thankfully, it’s pretty easy to add Rollbar tracking to your React error boundaries. We will show you how:

1. Open our previous <strong><a href="https://codepen.io/rollbar_example/pen/JrMGQq?editors=1011" target="_blank">Codepen example</a></strong> which has error boundaries configured.
2. Notice the first part of our JavaScript code, which configures and loads Rollbar. You can find the full details on how it works in our **[JavaScript documentation](https://rollbar.com/docs/notifier/rollbar.js)**.

   ```js
   var _rollbarConfig = {
      accessToken: "3cda8fbafbfe4a6599d1954b1f1a246e",
      captureUncaught: true,
      captureUnhandledRejections: true,
      payload: {
        environment: "production"
      }
   };

   !function(r){function o(n){if(e[n])return e[n].exports...
   ```

3. Add Rollbar error tracking to the error boundary’s `componentDidCatch` method.
   
   ```js
   componentDidCatch(error, errorInfo) {    
     Rollbar.error(error); // Send it to Rollbar!
   }
   ```

4. Load the page and trigger the error by clicking 5 times. Then, see what these errors look like in our public demo account’s **[Items page](https://rollbar.com/demo/demo/items/)**. You don’t need to sign up since this account is open to everyone.

![Items screenshot](https://rollbar.com/assets/blog/images/2017-10-11-react-error-boundaries/image1.png)

5. Get more details by clicking on the item near the top of the list that says “Uncaught Error: I crashed!” You can now see a traceback and **[telemetry](https://rollbar.com/blog/introducing-javascript-telemetry/)** recording what happened before the error occurred. This provides more context to help you find the root cause of errors.

![Item detail screenshot](https://rollbar.com/assets/blog/images/2017-10-11-react-error-boundaries/image2.png)

We highly recommend you add error boundaries to your React applications. They are very easy to use, and not only help you provide a graceful recovery, but also report those errors to Rollbar so you can quickly fix errors before they impact more users.

_This article was originally published on [Rollbar's blog](https://rollbar.com/blog/react-error-boundaries/)._