Course contentsShow
← React
Lesson 1847 of 2,39643. RoutingFree lesson

Loader Error Handling with errorElement

How thrown errors and rejected promises in loaders render error boundaries at the route level.

Loader Error Handling with errorElement

What you'll learn: How to gracefully handle errors thrown in route loaders using React Router's errorElement.

The Problem with Loader Errors

When a loader fetches data, things can go wrong—network failures, 404s, authorization issues. Without proper handling, these errors crash your app or leave users staring at blank screens. React Router's data router provides a built-in solution: the errorElement property.

How errorElement Works

When a loader throws an error (via throw new Error()) or returns a rejected promise, React Router stops the normal rendering flow and renders the errorElement instead. This acts like an error boundary specifically for that route:

const router = createBrowserRouter([
  {
    path: '/user/:id',
    element: <UserProfile />,
    loader: async ({ params }) => {
      const response = await fetch(`/api/users/${params.id}`);
      if (!response.ok) {
        throw new Response('User not found', { status: 404 });
      }
      return response.json();
    },
    errorElement: <ErrorPage />
  }
]);

If the fetch fails or returns a 404, <ErrorPage /> renders instead of <UserProfile />. The error doesn't bubble up to crash your whole app—it's contained at the route level.

Why This Matters

Think of errorElement as a safety net under each route. Just like a circus performer has a net for their specific act, each route can have its own error handler. Parent routes can also provide fallback errorElement components that catch errors from any child route without a specific handler.

You can throw regular errors, Response objects (for HTTP-like errors), or let promise rejections flow naturally—React Router catches them all.

Key Takeaway: errorElement lets you render route-specific error UI when loaders throw errors or reject promises, preventing crashes and keeping errors isolated to the affected route.