I am learning how to use react-router-dom
. I have just encountered the errorElement
prop in the createBrowserRouter
function. I understand how the errorElement
prop works, but I don't understand when I should choose error boundaries instead of errorElement
. They can perform the same task, but which one should I use and why?
According to the docs, the errorElement
:
errorElement
When exceptions are thrown in loaders, actions, or component rendering, instead of the normal render path for your Routes (
<Route element>
), the error path will be rendered (<Route errorElement>
) and the error made available withuseRouteError
.This feature only works if using a data router like
createBrowserRouter
The Route
component's errorElement
is useful for the specific occasions an error is thrown during processing a route's loader or action functions or when rendering the routed component and you can render more specific and useful UI whereas the regular React error boundaries are more for unexpected errors. You can narrow the scope of a React error boundary to display specific UI, but the benefit of the errorElement
is the easier to use API abstraction. You don't need to implement the catch/handling logic yourself in a custom error boundary component (React class component only), but rather you can use the useRouteError
hook to access the error that was thrown and you can focus more on the UI.
If you are working with react-router
data routers and routes, and route loaders and actions, then using the errorElement
seems the rather clear & obvious choice.