/    /  ReactJS- React Error Boundaries

React Error Boundaries

 

In the past, if we get any JavaScript errors inside react UI components module, it corrupts the React?s internal react state and put React in a broken react state on the next to react renders. No way to handle these javascript errors in React UI components. Does not it any javascript methods to recover from them. But, React 16 new version introduces a new concept to handle javascript errors by providing the react error boundaries. Now, if any JavaScript error is found in a part of the UI component, it does not break the whole web app.

Error boundaries are React UI components that catch JavaScript errors anywhere in our web app, log those javascript errors, and display fallback UI components. It does not break the whole web app UI component tree and only renders the fallback UI whenever an error occurred in a component. Error boundaries catch errors during rendering in UI component react lifecycle methods and constructors of the whole tree below them.

 

Error boundary in class:

A class UI component can becomes an react error boundary if it defines a new react lifecycle methods either static getDerivedStateFromError() or componentDidCatch(error, info). We can use react static getDerivedStateFromError() to react render a fallback UI when an error has been thrown, and can use componentDidCatch() to log error information.

A react error boundary can’t catch the error within itself. If the react error boundary fails to react render the error message, the error will go to the closest error boundary above it. It is similar to the catch {} block in JS(JavaScript).

 

How to implement error boundaries:

Step-1 Create a class that extends React component and passes the props inside it.

Step-2 Now, add the componentDidCatch() method which allows you to catch errors in the components below them in the tree.

Step-3 Next add the render() method, which is responsible for how the component should be rendered. For example, it will display an error message like “Something is wrong.”