React error boundaries

Published under React.

React error boundaries allow you to prevent your React application from completely crashing in the event of an error in your code. 

You can read more about React's error boundaries on their documentation page.

The key point to understand when using error boundaries is this snippet from the docs:

catch JavaScript errors anywhere in their child component tree

Specifically, "component tree". If you try to use Error Boundaries in the following way, none of your errors will be caught:

In the example above, CustomErrorCatcher is our class component that implements our error boundary logic.

The code that is throwing an error, {invalidVariable}, is rendering inside the CustomErrorCatcher component, instead of in a child component. This is what prevents the error boundary from catching the error. The error boundary will onlycatch errors in child components.

So instead, I recommend you do something like this at the top-level of your application:

This way your entire application is wrapped in an error boundary, in the event that any of your components throw an error.

Thanks for reading!

Did you find this post useful? Let me know on Twitter! If you found an issue with the content, submit a pull request!

Subscribe to my newsletter to know when I publish more content in the future.

❤️ Likes: 0
📣 Retweets: 0
💬 Replies: 0
🙊 Mentions: 0