DEV Community

Cover image for How to handle errors effectively in React JS?
Jyotishman Saikia
Jyotishman Saikia

Posted on

How to handle errors effectively in React JS?

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

Top comments (2)

Collapse
 
fjones profile image
FJones • Edited

Please don't use unnecessary plugins just to avoid writing class components. Writing a single ErrorBoundary class component and wrapping that in a functional HOC is easy and lightweight enough, and allows you much more flexibility in rendering and hooking into the error-capturing code. It also lets you reuse the error boundary visual components outside of explicit React error propagation.

Collapse
 
jyotishman profile image
Jyotishman Saikia

Thanks FJones for the feedback!
Would be great if you can provide a codepen for it.