DEV Community

Mayuran
Mayuran

Posted on

13 4

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.

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (4)

Collapse
 
toddhgardner profile image
Todd H. Gardner

Nice job! A bug free app makes the whole web better.

Collapse
 
chrisachard profile image
Chris Achard

Very nice! I didn't know about Error Boundary - I'll be able to use this. Thanks!

Collapse
 
sayali0710 profile image
sayali0710

Can we use a different error boundary to wrap an error inside a functional component

Collapse
 
maybebored profile image
Mayuran

Hi, please elaborate what you mean? If you mean can you have more than one error boundary, yes that is possible. It's just a wrapper that will handle any Exception that is thrown from the child component, that it is wrapping.

Hot sauce if you're wrong - web dev trivia for staff engineers

Hot sauce if you're wrong · web dev trivia for staff engineers (Chris vs Jeremy, Leet Heat S1.E4)

  • Shipping Fast: Test your knowledge of deployment strategies and techniques
  • Authentication: Prove you know your OAuth from your JWT
  • CSS: Demonstrate your styling expertise under pressure
  • Acronyms: Decode the alphabet soup of web development
  • Accessibility: Show your commitment to building for everyone

Contestants must answer rapid-fire questions across the full stack of modern web development. Get it right, earn points. Get it wrong? The spice level goes up!

Watch Video 🌶️🔥

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay