×

React Error Boundaries

React Error Boundaries

In the past, the errors of JavaScript within the components were used to corrupt the internal state of react and cause it to emit the cryptic errors on the next renders. These errors were always because of a previous error in the application code, but there was not any way in react to handle them gracefully in components, and also we could not recover them.

React 16 introduces the new concept of handling the errors is by Error Boundaries. Error boundaries are the components of react that catch the errors of JavaScript anywhere in their child component tree, log those errors, and will display a fallback UI rather than the component tree that crashed.

Error boundaries catch errors during rendering, within lifecycle methods, and in the constructors of the whole tree below them.

Error boundaries do not catch the errors for Event handlers, Asynchronous code, server-side rendering, errors thrown in the error boundary itself.

For a simple application of react, you can declare the error boundary once and can use it for the complete application. For complex applications having multiple components, you can declare multiple error boundaries to recover every part of the entire application.

Error Boundary in class

A class will be an error boundary if it defines both of the lifecycle methods static getDerivedStateFromError() or componentDidCatch(). The use of static getDerivedStateFromError() is for rendering a fallback UI after an error has been thrown. The use of componentDidCatch() is for logging the error information.

For the components, Error boundaries work as a catch {} block of JavaScript. Only the class components can be error boundaries. An error boundary cannot catch the error within itself. If the error boundary fails in the rendering of an error message, then the error will propagate to the nearest error boundary above it. This is also similar to how the catch {} block works in JavaScript.

Implementation of Error Boundaries

Let us try to understand the implementation of error boundaries by using the following example:

class ErrorBoundaryExample extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
// Update the state so the next render show the fallback UI.
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
// We can also log the error for an error reporting service
logErrorToMyService(error, errorInfo);
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UI 
return <div>Something went wrong.</div>;
}
return this.props.children; 
}
} 

Now, you can use it as a regular component. Add the new component in HTML, which you require to add in the error boundary. In this example, we are adding a Widget component.

  
  

Where to Place Error Boundaries

The error boundary entirely depends on you. You can use the error-boundaries at the top-level of the application components or wrap it on the individual components for protecting them from the breaking of other parts of the application.

Example of using Error-boundary:

Let us see an example of it:

App.js

import React, { Component } from 'react';
import './App.css';
import Actors from './Actors';
class App extends Component {
render() {
return (

Actors Performing at Tonight in the show

); } } export default App;

Actors.js

import React from 'react';
function Actors({actorName}) {
if (actorName === 'Govinda') {
throw new Error ('not performing tonight!')
}
return (
{actorName}
) } export default Actors;

Output:

Actor Performing tonight show

If you change one of the artist names to 'Govinda’ like <Actors actorName='Govinda'></Actors> then you will see the following:

Where to Place Error Boundaries

New Behavior for uncaught errors

If the error doesn't catch by any error boundary, it will result in the unmounting of the complete React application. It is the new implication in the error boundaries.

Error Boundaries inside Event Handlers

As stated above, error boundaries do not catch the errors in event handlers. React does not require any error boundary to recover from errors inside event handlers.

If you have to catch the error within the event handler, you should use the regular JavaScript try/catch statement as shown in the following example:

class App extends React.Component {
constructor(props) {
super(props);
this.state = { error: null };
this.handleClick = this.handleClick.bind(this);
}
handleClick() { 
try {
// Do something that can throw the error
} catch (error) {
this.setState({ error });
}
}
render() {
if (this.state.error) {
return 

Caught an error.

} return
Click Me
} }

It is to be noted that the above example is demonstrating the behavior of regular JavaScript and does not use the error boundaries.


Related Topics

React State

React State The state is an updatable structure which is used for containing data or information about the component. The state in a component can be changed over time. The change...

3 minutes read.

ReactJS vs AngularJS

Difference between ReactJS and AngularJS AngularJS AngularJS is the JavaScript framework that is open source, and it is also used to build a dynamic web application. It is developed in 2009 by...

5 minutes read.

React Component API

React Component API It is a top-level API. It provides reusability to the code in the application and makes it completely individual. It has several methods for: Creating Elements.Transforming Elements.Fragments. Now, we are explaining the three...

2 minutes read.

React Props Validation

React Props Validation As we know, props are a suitable mechanism for passing the read-only attributes to react components. The props are required to be correctly used in the component. If it is...

5 minutes read.

React Animation

React Animation The animation is a procedure in which an image is manipulated to appear as a moving image. It is widely used to create an interactive web application. In React, we have to...

4 minutes read.

Pros and Cons of ReactJS

Pros and Cons of ReactJS There are various advantages, and disadvantages of ReactJS are as follows: Benefits of ReactJS 1. Easy to Learn and Use: ReactJS is very easy to use and learn. It has a good...

3 minutes read.

ReactJS Versions

ReactJS Versions The Complete set of release history of ReactJS is elaborated as follows. The complete set of full documentation of recent releases is on GitHub. S.noVersionRelease DateExplanation1.0.3.029/05/2013Initially released for public.2.0.4.029/07/2013Supporting comments...

4 minutes read.

React Refs

React Refs The word ‘Refs’ is an abbreviation of ‘References’ in React. It is as similar as Keys in React. Refs are a function in React which is used for accessing the DOM element and...

7 minutes read.

React Native vs ReactJS

Difference between React Native and ReactJS React Native React Native is also an open-source JavaScript framework that is used for the development of a mobile application for iOS Android and Windows. It...

6 minutes read.

React Conditional Rendering

React Conditional Rendering In React, the working of the conditional rendering is similar to the condition works in JavaScript. We use JavaScript operators for creating elements that represent the current state, and then the React...

3 minutes read.

React Forms

React Forms Forms are the important part of any web application. It allows the interaction of the user with the app as well as the gathering of the information from the...

3 minutes read.

React Component Life-Cycle

React Component Life-Cycle In ReactJS, the creation process of every component includes several lifecycle methods. These methods, together stated as component's lifecycle. Four phases of the component's life cycle are as...

4 minutes read.

React Map

React Map The map() is the standard function of JavaScript, which can be called at any array. The map() method is used for traversing and displaying a list of the similar objects of...

2 minutes read.

React Error Boundaries

React Error Boundaries In the past, the errors of JavaScript within the components were used to corrupt the internal state of react and cause it to emit the cryptic errors on the next...

3 minutes read.

React Hooks

React Hooks The Hooks were introduced in React 16.8. By using React Hooks, you can use the state and other features of the React without writing a class. Hooks do not work within the classes....

5 minutes read.

React Lists

React Lists Lists are used for displaying the data in an ordered format and mainly used to display the menus on websites. The creating of lists in React is as similar...

2 minutes read.

React Table

React Table The table represents an arrangement that organizes the information in the form of rows and columns. The table is mainly used for storing and displaying the data within a structured format. Features of...

2 minutes read.

React Environment Setup Step by Step

React Environment Setup This section will provide you the information about how to set up an environment for the successful development of ReactJS application: Pre-Requisite for ReactJS NodeJS and NPMReact and React DOMWebpackBabel There are two...

5 minutes read.

React Constructors

What is constructor? The constructor is a method that is used for initializing the state of the object in the class. It calls automatically during the creation of an object in...

4 minutes read.

React JSX

React JSX As we know, all of the React components include a render function. The Render function specifies the HTML output of a React component. JSX is an acronym of JavaScript extension that...

3 minutes read.