Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does an error result in a blank screen instead of a message?

Tags:

reactjs

When I get a Javascript error, the screen goes blank. How do I get React to show error messages on the browser window?

like image 875
Ian Warburton Avatar asked Apr 19 '18 15:04

Ian Warburton


1 Answers

If the error happens during rendering there is no generic way for react to recover from it. The state of your app is corrupted and react doesn't know how to revert it to a valid state than can be rendered without errors. Therefore everything gets unmounted as a last resort.

In earlier versions of React (<16) the latest rendered UI was left in place. However the react team decided that it is considered worse to leave a potentially corrupted UI in place then to display no UI at all.

From the docs:

As of React 16, errors that were not caught by any error boundary will result in unmounting of the whole React component tree.

We debated this decision, but in our experience it is worse to leave corrupted UI in place than to completely remove it. For example, in a product like Messenger leaving the broken UI visible could lead to somebody sending a message to the wrong person. Similarly, it is worse for a payments app to display a wrong amount than to render nothing.

To handle errors for a certain part of your component tree add Error Boundaries to it. This way you can prevent your app from getting entirely unusable if the error happened in a part that is unrelated.

Note that error boundaries can only catch errors during rendering, in lifecycle methods, and in constructors of the whole tree below them.

Note

Error boundaries do not catch errors for:

  • Event handlers (learn more)
  • Asynchronous code (e.g. setTimeout or requestAnimationFrame callbacks)
  • Server side rendering
  • Errors thrown in the error boundary itself (rather than its children)
like image 148
trixn Avatar answered Oct 26 '22 08:10

trixn