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

Route Loaders: Fetching Before Render

How loader functions run before components render, receiving params and request objects.

Route Loaders: Fetching Before Render

You'll learn: How React Router's loader functions fetch data before a route's component renders, eliminating loading spinners and race conditions.

What Are Route Loaders?

With the data router (createBrowserRouter), you can define a loader function for each route. This function runs before the route's component renders, allowing you to fetch data upfront rather than triggering effects inside the component.

Think of it like a restaurant: instead of sitting down and then waiting for your food (component renders, then fetches), the loader prepares your meal while you're walking to your table. By the time you sit, it's ready.

How Loaders Work

Each loader receives two arguments:

  1. params – The dynamic segments from the URL (e.g., userId from /users/:userId)
  2. request – A Web Request object containing URL search params, headers, and more

The loader returns the data (or a promise), and React Router waits for it to resolve before rendering the component. You access this data inside your component using useLoaderData().

// Route definition
{
  path: '/users/:userId',
  element: <UserProfile />,
  loader: ({ params, request }) => {
    // params.userId is available here
    // request.url gives you the full URL
    return fetch(`/api/users/${params.userId}`);
  }
}

The loader runs on navigation, not on component mount. If the user navigates from /users/1 to /users/2, the loader runs again with the new params.

Why This Matters

Loaders eliminate the "fetch-on-render" pattern, where components show loading states while data trickles in. Data is ready immediately when the route renders.

Key Takeaway: Loaders run before route components render, receiving params and request objects, ensuring data is available synchronously via useLoaderData() without loading states.