DEV Community 👩‍💻👨‍💻


Posted on

How To Use React Error Boundary


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')) {
 } else {
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 (
            className=`btn ${this.state.color}`
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.


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.

Top comments (4)

toddhgardner profile image
Todd H. Gardner

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

chrisachard profile image
Chris Achard

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

sayali0710 profile image

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

maybebored profile image

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.

Need a better mental model for async/await?

Check out this classic DEV post on the subject.

⭐️🎀 JavaScript Visualized: Promises & Async/Await

async await