×

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 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 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.

How to use React Context

React Context React Context is used to pass the data through the component tree without passing the props down manually at the every level. In React Application, the data is passed in a top-down approach...

4 minutes read.

React Events

React Events An event is an action that triggers a response of the user action or system-generated event. As HTML, React can also perform actions based on user events. React has the...

2 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.

Difference Between State and Props in React

Comparison between State and Props 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...

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 Code Splitting

React Code Splitting React Code Splitting is the procedure of splitting the bundle files by which the files get easily loaded on the webpage. The react application bundles the files by using...

4 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 Bootstrap

React Bootstrap React has a widely used JavaScript framework for creating web applications, and Bootstrap has become the most popular CSS framework. Single-page apps have become popular from the last few...

9 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.

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 Router

What is React Router? Routing is a process by which a user can direct to different pages based on their actions and requests. ReactJS router is generally used to develop single...

10 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.

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 Flux

React Flux Introduction It is an application architecture that is internally used by Facebook to build the client-web application with react. It is useful when the project includes dynamic data, and...

2 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.

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 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.

Comparison between React and Vue

Comparison between React and Vue React, and Vue both are the two most famous libraries of JavaScript that are used for creating thousands of websites today. The React and Vue both...

3 minutes read.