Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to prevent a broken react render from crashing the whole page?

Tags:

reactjs

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.

like image 402
temporary_user_name Avatar asked Oct 17 '25 16:10

temporary_user_name


1 Answers

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.

like image 93
Jakub Kosiński Avatar answered Oct 20 '25 06:10

Jakub Kosiński



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!