Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

What are error boundaries in ReactJS (16) ?

  • Last Updated : 09 Sep, 2021

Runtime errors during rendering could put out an application in a broken state. React basically unmounts the hole react component tree. What would be great is if we could catch the errors anywhere in their component tree, log those errors, and display a fallback UI. This is where the error boundary takes the spotlight. A class component that implements either one or both of the life cycle methods static getDerivedStateFromError() or componentDidCatch() becomes an error boundary.The static getDerivedStateFromError() is used to render a fallback UI after an error is thrown. The componentDidCatch() is used to log the error information.

Error boundaries don’t catch errors for:

  • Event handlers
  • Asynchronous code (e.g. setTimeout or network request )
  • Server Side rendering
  • Errors thrown in the error boundary itself (rather than its children)

Let’s see an example without using Error Boundary

Creating React Application:

Step 1: Create a React application using the following command:

npx create-react-app error-boundary-demo

 



Step 2: After creating your project folder i.e. error-boundary-demo, move to it using the following command:

cd error-boundary-demo

Step 3: Create a directory and name it Component.

mkdir Component

Project Structure:  It will look like the following.

Step 4: In this step, we will create HeroViewar component to print the hero’s name. This component throws an error if hero’s name is ‘Joker’. Create HeroViewar.js in the Component directory and write down the following code. 

HeroViewar.js




import React from 'react'
  
const HeroViewar = ({name}) => {
  
    // Throw an error if not hero
    if(name === "Joker")
        throw new Error("Not a Hero!")
    return(
        <h2>{name}</h2>
    )
}
  
export default HeroViewar

 



Step 5: In this step, we will import HeroViewar from HeroViewar.js to print some hero’s name. Pass hero’s name as prop to HeroViewar component. Write down the following code in the App.js file.

App.js




import React from 'react'
import HeroViewar from './Component/HeroViewar'
  
const App = () => {
  return (
    <>
      <HeroViewar name="Superman" />
      <HeroViewar name="Batman" />
      <HeroViewar name="Joker" />
    </>
  )
}
  
export default App

Step to Run Application: Run the application using the following command from the root directory of the project:

npm start

Output:

Explanation: One of our hero’s name was ‘Joker’, that’s why HeroViewar throws an error. If you now take a look at the browser you will see the entire application crashes. Obviously, this is not good. What we want is if a particular component throws an error only that component should fall back into a UI and the remaining component should be unaffected. 

Step 6: To overcome the above problem React 16 introduce a new concept of an “error boundary”. Error Boundary catch the errors anywhere in their component tree, and display a fallback UI. Let’s add it.  Create ErrorBoundary.js in the Component directory and write down the following code. 

ErrorBoundary.js




import React, { Component } from 'react'
  
class ErrorBoundary extends Component {
    constructor(props) {
        super(props)
        this.state = { hasError: false }
    }
      
    static getDerivedStateFromError(error){
  
        // Update state so the next render
        // will show the fallback UI.
        return { hasError: true }
    }
  
    componentDidCatch(error, errorInfo) {
  
        // You can also log the error to
        // an error reporting service
        console.log(error, errorInfo)
    }
  
    render() {
        if (this.state.hasError) {
  
          // You can render any custom fallback UI
          return <h2>Something went wrong!</h2>
        }    
        return this.props.children 
      }
}
  
export default ErrorBoundary

Step 7: Update App.js to wrap each and every HeroViewar  with ErrorBoundary like:

<ErrorBoundary>
    <HeroViewar name="..." />
</ErrorBoundary>

Write down the following code to App.js

App.js




import React from 'react'
import ErrorBoundary from './Component/ErrorBoundary'
import HeroViewar from './Component/HeroViewar'
  
const App = () => {
  return (
    <>
    <ErrorBoundary>
      <HeroViewar name="Superman" />
    </ErrorBoundary>
    <ErrorBoundary>
      <HeroViewar name="Batman" />
    </ErrorBoundary>
    <ErrorBoundary>
      <HeroViewar name="Joker" />
    </ErrorBoundary>
    </>
  )
}
  
export default App

Output:




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!