Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to prevent React from recreating component tree on error?

I'm working on an app, which throws an error somewhere within a React component, so in the console there's this error:

React will try to recreate this component tree from scratch using the error boundary you provided

I don't really get why React is even doing this since it's obviously going to result in an infinite render loop (and it does), since the error will keep happening every time it re-render.

So I'm wondering, can this behaviour be disabled somewhere? I'm not sure what is causing it, if it's just React or some other plugin. Any help would be appreciated.

like image 739
laurent Avatar asked Jan 31 '19 11:01

laurent


People also ask

What will happen when a component in React component tree throws an error?

React components that catch JavaScript errors anywhere in their child component tree, log those errors, and display a fallback UI. It catches errors during rendering, in lifecycle methods, etc.

How do you handle error boundaries in functional components?

In order to use Error Boundary in Functional Component, I use react-error-boundary. When we run this application, we will get a nice error display form the content of ErrorHandler component. React error boundary catches any error from the components below them in the tree.

How do you handle error response in React?

Error handling with Error Boundaries — For class components. Error boundaries are the most straightforward and effective way to handle errors that occur within your React components. You can create an error boundary component by including the life cycle method componentDidCatch(error, info) if you use class component.

What lifecycle method turns a component into an error boundary?

A class component becomes an error boundary if it defines either (or both) of the lifecycle methods static getDerivedStateFromError() or componentDidCatch() . Use static getDerivedStateFromError() to render a fallback UI after an error has been thrown. Use componentDidCatch() to log error information.


1 Answers

After a lot of digging I've managed to sort it out.

I've found the solution on react-hot-loader repo. As they say:

On Hot Module Update we will inject componentDidCatch and a special render
to every Class-based component you have, making Error Boundaries more local.

So, two possible solutions:

  1. Change your class component to a functional component.
  2. You can write your own error reporter (as it's specified here).

For me, both of this worked.

like image 131
Bogdan Mihai Avatar answered Sep 29 '22 14:09

Bogdan Mihai