When I get a Javascript error, the screen goes blank. How do I get React to show error messages on the browser window?
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
orrequestAnimationFrame
callbacks)- Server side rendering
- Errors thrown in the error boundary itself (rather than its children)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With