Error handling in React

Error handling should be the most important part of the large scale application so today we’ll show you the error handling in React using componentDidCatch method.

There are different types of error handling exist in the application but here we’ll handle the javascript error that occurs in React components.

By default the white screen will display when error will occur in the react application. So it’s good practice to handle an error to display a helpful message on screen. You can also log those messages for further use.

Steps to handle an errors in React

  1. Setup react application
  2. Create error handler component
  3. Output

1. Setup react application

Let’s set up a simple react application using create-react-app. If you don’t know how to do it then refer to the below link.

Create React Application

2. Create error handler component

We will create a component name as ErrorHandler.js that helps us to handle javascript error anywhere from the child components. It’s introduced as an error boundary.

In this component, we need to use componentDidCatch(error, info) lifecycle method to handle an error and display a fallback UI via state variable.

ErrorHandler.js

In the above component, we have used the state variable to display fallback UI. Also we used the componentDidCatch(error, info) lifecycle method to handle the error same as the try/catch.

To test the above code, we will throw an error from the <App /> component on page load and that component will be wrapped by the <Errorhandler /> component in index.js.

index.js

App.js

3. Output

Finally, run the project and see the output as below.

Output - Error handling in React - Clue Mediator
Output – Error handling in React – Clue Mediator

Note: A lot of people are saying that the error handling is not working or the componentDidCatch lifecycle method doesn’t work. But let me clear you that it handles only javascript errors and this will work for child components only there for you can not handle the error of the <ErrorHandler /> component.

Demo & Source Code

Github Repository

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *