Before we wrap up, we should discuss when and where to use error boundaries to maximize their potential impact, as well as their limitations.
Keep It Focused
Error boundaries isolate a component tree from the rest of the application and render a fallback UI when an error occurs. However, if our error boundary is too far from the source of the error, then other nearby components will be swallowed up by the error.
For example, imagine if we were to put a single error boundary wrapped around the root component. An error is thrown somewhere in the application and the error boundary replaces the root component with a fallback UI. While the application hasn’t crashed, the user only sees the fallback UI and nothing else. This isn’t a great experience.
Instead, we want to try to put our error boundaries as close to the source of potential errors as possible. Often, this means placing our error boundaries around new features that have not been thoroughly tested yet. As our users interact with these new features, errors will be caught and, with detailed logging, we can hone in the location of our error boundaries over time.
There are some key limitations of error boundaries that should be noted however. According to the React docs:
Error boundaries can catch errors that occur during rendering, in lifecycle methods, and in constructors of the whole tree below them. Error boundaries do not catch errors for event handlers, asynchronous code, server side rendering, or errors thrown in the error boundary itself (rather than its children).
If you’d like to learn more about this topic, take a closer look at the React Error Boundaries docs and the react-error-boundary package docs. There, you’ll be able to learn more about how to handle errors that may not be caught by error boundaries or why
catch aren’t used for React components.