Handling Errors
In the first example at the very beginning of this chapter (where the HTTP request was sent with help of useEffect()
), the code did not just handle the success case but also possible errors. In all the React Router-based examples since then, error handling was omitted. Error handling was not discussed up to this point because while React Router plays an important role in error handling, it's vital to first gain a solid understanding of how React Router 6.4 works in general and how it helps with data fetching. But, of course, errors can't always be avoided and definitely should not be ignored.
Thankfully, handling errors is also very straightforward and easy when using React Router's data capabilities. You can set an errorElement
property on your route definitions and define the element that should be rendered when an error occurs:
// ... other imports import Error from './components/Error'; const router = createBrowserRouter([ { ...