How To Use React Error Boundary

maybebored

Mayuran

Posted on September 9, 2019

How To Use React Error Boundary

Recap

In a previous post, I explained how I came to find out about Error Boundary. In this post let us dive into it a bit more, and understand how React provides a declarative way to catch and handle errors that occur during rendering. Finally, I will show how I used it.

Declarative Error Handling

In a typical JavaScript code, errors can be caught and handled using a try - catch block.

try {
   throw new Error('A new error');
catch (error) {
   console.log('Caught this error', error);
}
Enter fullscreen mode Exit fullscreen mode

This is imperative code where we tell the program how to do something, usually in a series of steps. This is not the case when using React, where we tell the program what to do.

Let's take a look at code examples, I found elsewhere of both approaches, for doing the same task of changing a button element's colour

Imperative example, where we provide step-by-step instructions to change the change the button colour.

const container = document.getElementById('container');
const btn = document.createElement('button');
btn.className = 'btn red';
btn.onclick = function(event) {
 if (this.classList.contains('red')) {
   this.classList.remove('red');
   this.classList.add('blue');
 } else {
   this.classList.remove('blue');
   this.classList.add('red');
 }
};
container.appendChild(btn);
Enter fullscreen mode Exit fullscreen mode

React example, where we handle state and return the button element.

class Button extends React.Component{
  this.state = { 
     color: 'red' 
  }
  handleChange = () => {
    const color = this.state.color === 'red' ? 'blue' : 'red';
    this.setState({ color });
  }
  render() {
    return (
       <div>
         <button 
            className=`btn ${this.state.color}`
            onClick={this.handleChange}>
         </button>
       </div>
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

We are only telling React what to return (display) given the current state of the program. Therefore using a try-catch block while trying to render a component will not catch errors in the component. React Error Boundary is a declarative approach to error handling.

How I used React Error Boundary

Using Error Boundary helps render a fallback UI, which is better UX than a blank screen, but we can do better. We can reset the state so users can go back to what they saw before the error occurred, without having to reload the page.

The fallback UI can contain a button, which when clicked, sets the component's state to its initial state, that is {hasError: false}. But before it does this we must reset the state of the child component that is rendered within the Error Boundary, so that when the app re renders we are not in an erroneous state. See for yourself below.

Conclusion

With that I conclude my two part series on React Error Boundary. The last bit about resetting state is just something I experimented with, I didn't find anything online that endorses that, so I appreciate any feedback on that.

💖 💪 🙅 🚩
maybebored
Mayuran

Posted on September 9, 2019

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related