If a breaking error occurs in a React component, the whole page crashes. For instance, if x
is null and you try to access x.someProperty
, you'll get an error and the whole page will go white. This is a little bit different from an old-style app that isn't running entirely on JS, because the markup (HTML&CSS) would still be there even if the JS errored out and blocked some aspects of the page.
Is there a way to mitigate this with React? Something like wrapping a component in a try/catch so that if something goes wrong, only that component fails and only that part of the page goes white, rather than the entire page. I'm not sure if there's a better pattern than literally wrapping the entire body of a functional component's code in a try/catch.
I suppose I'm particularly interested in functional components here, but a class-based answer might be useful for someone else.
You can mitigate such errors using Error Boundaries - such components may catch errors thrown from the child components and display some meaningful error instead of just crashing.
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