React JS Error Boundaries

In react two error handling phase methos are available

  • 1. static getDerivedStateFromError(error)
  • 2. componentDidCatch(error, info)

The static method getDerivedStateFromError is used to render a fallback UI after an error is thrown and the componentDidCatch method is used to log the error information.

We can get more idea by looking below example. you can put this file in /src/components folder and put in /src/App.js file.

1. ParentComponent

import React, { Component } from 'react'; class ParentComponent extends Component { render() { return( <div> <Country name="India" /> <Country name="London" /> <Country name="Brazil" /> </div> ); } } export default ParentComponent;

2. ChildComponent

import React from 'react'; function Country({ name }) { if(name === 'London') { throw new Error('Not a country') } return ( <div> <div>{name}</div> </div> ) }

While we run above code, it will show error screen in browser. Actual error is in . rest of two component should works. now We have to handle this error.

Change in parent component as per below and add ErrorBoundary new component.

class ParentComponent extends Component { render() { return( <div> <ErrorBoundary> <Country name="India" /> </ErrorBoundary> <ErrorBoundary> <Country name="London" /> </ErrorBoundary> <ErrorBoundary> <Country name="Brazil" /> </ErrorBoundary> </div> ); } }

3. ErrorBoundary

import React, { Component } from 'react'; class ErrorBoundary extends Component { constructor(props) { super(props) this.state = { hasError: false } } static getDerivedStateFromError(error){ return { hasError:true } } render() { if(this.state.hasError) { return <h1> Something went Wrong </h1> } return this.props.childern } } export default ErrorBoundary;

Now, above code shows, in browser 'Something went Wrong' only for second country component. other component will show as it expected. Now we log this error to console by componentDidCatch. So, add below code in ErrorBoundary component.

componentDidCatch(error, info) { console.log(error); console.log(info); }


Error boundaries are React components that catch JavaScript error in their child component tree, log this error, and display a fall-back UI.

A class component becomes an Error Boundary by defining either or both of getDerivedStateFromError and componentDidCatch lifecycle methods.


← Previous

Next →