How to handle errors effectively in React JS?

Jyotishman Saikia - Jun 9 '21 - - Dev Community

Can you guess what is wrong with this code ?

image

If you ship this code to production, your users will see a white screen in your entire application.

image

And if you run this application in your development server you will get error like this-

image

So how to handle such errors so that our application doesn't crash in the production

One way is to add try/catch block in all our components inside the render or return statement. This can solve the issue.

But if our application is large and we have 100 components in our application , adding try/catch to all the components would be tiresome.

Here comes the role of React Error Boundary.

Error boundaries are React components that logs runtime errors anywhere in our child components and display a fallback UI instead of the component tree that crashed.

But to use React Error Boundary it has to be class component.

Fortunately! we have a plugin react-error-boundary to use it in our functional components.

So, let add react-boundary in our application.

App.jsx file

image

errorHandling.jsx

image

After we add the React error boundary plugin in our application, it will start logging for runtime error and we can add a fallback UI if any error occurs.

Finally! Instead of bank white screen we are able to see the fallback UI if any runtime error occurs.

image

. . . . . . . . . . . . . . . . . . . . .