Understanding Error Boundaries in React

Understanding Error Boundaries in React

Concept of Error Boundary

Have you been finding it difficult in understanding error boundaries in react? In this article, I will explain it to you, get a bottle of chilled coke and relax.

What is Error Boundary?

Error Boundaries are class-based React components that catch JavaScript errors anywhere in their child components, logs the errors, and display the user interface instead of the child components in which the error occurs.

Error Boundary was introduced in React 16.

Example of Error Boundary

First of all, let's create a separate component called User. Then, create a JavaScript error in it as shown below;

const User = ({username}) => {
if(username === 'Mark'){
   throw new Error('Error detected!')
}
  return (
       {username}
   )
}

export default User

Explanation

  • In the code above, we passed username as a prop.
  • Then checked if conditional is strictly equal to the variable 'Mark'.
  • If it is equal to it, throw an error
  • If it does equal, render the username value.

Setting up Error Boundary Component

As of today, error boundaries can only be set up in class-based components. Create a component and name it ErrorBoundary.

 import React from 'react'

class ErrorBoundary extends React.Component{
  constructor(props) {
        super(props)
         this.state = {
             hasError:  false
        }
    }

  static getDerivedStateFromError(error) {
      return { hasError: true}
}

 componentDidCatch(error, errorInfo) {
      console.log(error)
      console.log(errorInfo)
}

render(){
 if(this.state.hasError) {
  return <h1>Hay! I think something has gone wrong.</h1>
   }
return this.props.children
  }
}

Explanation

  • In the code above, the state is initially set to false.
  • If the code renders, getDerivedStateFromError() which is set to true is called.
  • This updates the states.
  • The fallback UI 'Hay I think something is wrong displays.'
  • Alongside with its children.

Where to Place Error Boundary

Where you decide to place the error boundary component solely depends on you and what you want to achieve.

Example

In App.js I can decide to wrap all the child components with one ErrorBoundary as shown below.

import React from 'react'
import Hero from './yourfile/path/'
import Error from './yourfile/path/'
import './App.css';

function App() {
  return (
    <div>
         <Error>
            <ThemeTogglerButton />
          </Error>
          <Error>
           <Hero heroName = "James"/>
          </Error>
          <Error>
           <Hero heroName= "Joker"/>
          </Error>
    </div>
  );
}

export default App;

Limitations of Error Boundaries

  • Do not catch errors inside event listeners. Hence you might need try and catch for that.
  • Do not catch errors for server-side rendering
  • Do not catch errors for Errors thrown in the error boundary itself (rather than its children)
  • Do not catch errors in asynchronous code (e.g. setTimeout or requestAnimationFrame callbacks)

The end

Thanks for reading :)