First off - if you haven't already I recommend giving my old React Error Boundaries blog post a read through, that post covers the basics of error boundaries. Once you've read it, jump back here to learn more!
Since I last published that blog post, there have been quite a few advancements in and around React, including but not limited to React Server Components!
Sadly however, we still need to use class components for error boundaries at the time of writing. Who knows, maybe in another 5 years this will have finally changed?!
My Go To Implementation
In most of my projects I reach for the following Error Boundary implementation, it offers a decent amount of flexibility where I want it, but also isn't too over the top.
This implementation is pretty simple, it uses the getDerivedStateFromError
lifecycle method to catch any errors thrown from its children. If an error is caught, it will render the fallback
component, passing in the error and a reset
function.
This reset
function can be used to reset the error state, allowing the user to retry whatever action caused the error in the first place.
Here's an example implementation: