Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 50 ยท Data Mode

Loaders: Data Before Render

Learn React Router loaders: fetch data before a route renders, read it with useLoaderData, use params and request, load nested routes in parallel and throw responses.

The classic way to show data in React is to render the component first, then fetch in an effect, then render again with the result. That works, but it has a cost: the user sees an empty screen and a spinner on every page, and when a page has nested components that each fetch their own data, the requests can run one after another. The page appears slowly even though each request is fast.

A loader moves the fetching out of the component and into the route. It is a function you attach to a route object. When the user navigates to that route, the router calls the loader first, waits for it to finish, and only then renders the page, which reads the finished data with useLoaderData. In this lesson you will write loaders, see how they get the URL's params and query string, learn why nested loaders run in parallel, and learn how to fail properly by throwing a response.

You need a data router for all of this, so read createBrowserRouter and RouterProvider first. If you are comfortable with fetching in effects, Data Fetching in the React tutorial shows what loaders replace.

A first loader

This is the real React Router API, shown read-only:

JSX
// Real React Router (data mode), read-only
import { createBrowserRouter, useLoaderData } from 'react-router';

async function productLoader({ params }) {
  const response = await fetch('/api/products/' + params.id);
  if (!response.ok) {
    throw new Response('Product not found', { status: 404 });
  }
  return response.json();
}

function ProductPage() {
  const product = useLoaderData();
  return (
    <article>
      <h1>{product.name}</h1>
      <p>{product.price} USD</p>
    </article>
  );
}

const router = createBrowserRouter([
  {
    path: '/products/:id',
    loader: productLoader,
    Component: ProductPage,
  },
]);

Notice what is missing from ProductPage: no useEffect, no useState for the data, no isLoading flag, and no if (!product) return null. By the time the component renders, product exists. The component describes how to show the data, and the loader describes how to get it.

sequenceDiagram
  participant U as User
  participant R as Router
  participant L as Loader
  participant C as Component
  U->>R: clicks a link to /products/7
  R->>L: call loader with params and request
  L-->>R: resolved data
  R->>C: render, data via useLoaderData
  C-->>U: finished page

During the wait, the old page stays on screen. The new page appears only when its data is ready.

What a loader receives

A loader is called with one object. You will use two of its fields most of the time.

  • params: the dynamic segments of the matched route, such as { id: '7' } for /products/:id. They are always strings. See Dynamic Segments and useParams.
  • request: a standard Fetch API Request for the navigation. Its url is the full URL, so you read the query string from it. Its signal is an AbortSignal that fires when the navigation is cancelled, for example when the user clicks another link before the loader has finished.
JSX
// Real React Router, read-only
async function searchLoader({ request }) {
  const url = new URL(request.url);
  const query = url.searchParams.get('q') ?? '';
  const page = Number(url.searchParams.get('page') ?? '1');

  const response = await fetch(
    '/api/products?q=' + encodeURIComponent(query) + '&page=' + page,
    { signal: request.signal } // stop the fetch if the user navigates away
  );
  return { query, page, results: await response.json() };
}

Passing request.signal to fetch is a small habit with a real benefit: if the user clicks quickly through several pages, abandoned requests are cancelled instead of piling up. The router already ignores the stale results, but cancelling saves bandwidth and server work.

A loader may return any value: an object, an array, a number, or a Response. Returning plain objects is the simplest. If you need to set a status code or headers on the result, use the data() helper from react-router, for example return data(product, { status: 200, headers: {...} }). (Older code uses a json() helper; with plain objects you do not need it.)

Because the router calls the loader when you navigate, the loader runs again when:

  • the route's params change (/products/7 to /products/8),
  • the search params change (?page=1 to ?page=2),
  • an action finishes, so the page shows fresh data (this is called revalidation, see Revalidation and Caching).

It does not run again when the component simply re-renders for another reason, such as a state change. The data stays the same until the next navigation.

Try it: a loader-like stand-in

The sandbox cannot run React Router, so this stand-in builds the core behavior of a data router. Each route object has an async loader. On navigation the stand-in marks navigation: loading, calls every loader of the matched routes at the same time, waits for all of them, and then commits the new page. A reused parent loader is skipped, which is also what the real router does while a parent route's params stay the same.

The log below the page shows what happened. First load the app and read the log, then click Product 2, and then Product 99, which throws a Response with status 404.

Parallel loaders and a thrown 404

On the first load the log reads start root, start home, done root, done home: both loaders started before either finished, because the stand-in calls them together. Click "Product 2" and the log becomes reuse root, start product, done product: the root layout's data is kept because its params did not change. Click "Product 99" and the loader throws; the stand-in shows an error in place of the page, a simplified version of what an errorElement does in the real router.

The stand-in is honest about its limits. It has no request, no abort signal, no revalidation and a single global error display instead of a nearest-error-boundary lookup. The real router does all of those.

Nested loaders run in parallel

A URL like /dashboard/reports/7 can match three routes at once: a dashboard layout, a reports section and a single report. Each can have its own loader. The router starts all of them at the same time when you navigate there. The page renders when the slowest one finishes, not after the sum.

This is the opposite of the "fetch in components" pattern. There, the dashboard component renders first and starts its fetch, then its child renders and starts another, then the grandchild: each request waits for the render of the one before it. That chain is called a request waterfall. The next demo shows the difference with numbers. Move the sliders and compare.

flowchart LR
  subgraph W["Fetch in components (waterfall)"]
    direction LR
    W1["parent<br/>renders, fetches"] --> W2["child<br/>renders, fetches"] --> W3["grandchild<br/>renders, fetches"]
  end
  subgraph P["Route loaders (parallel)"]
    direction TB
    P1["parent loader"]
    P2["child loader"]
    P3["grandchild loader"]
  end

Components can only start fetching once their parent has rendered. Loaders for all matched routes start together.

Waterfall versus parallel timing

With the default values, the waterfall needs 900ms (300 + 400 + 200) and the loaders need 400ms (the slowest one). The more nested levels fetch independently, the bigger the gap.

Parallel loading has one catch: a child loader cannot read its parent's loader data, because they start at the same time. If the child needs something the parent computes, either repeat the cheap work in the child (read the session, look up the id), cache the shared request so both calls reuse it, or restructure so that one loader fetches what both need. A component can read the data of a parent route with useRouteLoaderData('routeId'), but only after rendering, never inside a loader.

Failing properly: throw a Response

A loader has three ways to end:

  1. Return data. The page renders.
  2. Throw a Response, for expected failures such as "not found" or "forbidden". The router renders the route's error element and gives it the status. See Error Boundaries and Error Elements.
  3. Throw a redirect, to send the user elsewhere, for example to a login page.
JSX
// Real React Router, read-only
import { redirect } from 'react-router';

async function accountLoader({ request }) {
  const user = await getCurrentUser();
  if (!user) {
    const from = new URL(request.url).pathname;
    throw redirect('/login?from=' + encodeURIComponent(from));
  }
  if (!user.emailVerified) {
    throw new Response('Please verify your email first', { status: 403 });
  }
  return user;
}

Throwing instead of returning keeps the happy path clean: the component only ever sees valid data, because every problem was dealt with before it rendered. Anything else the loader throws, such as a network TypeError, also goes to the error element as an unexpected error.

In data mode, loaders run in the browser. Never put API keys or database passwords in them, and never rely on a loader redirect to protect private data: the server must still check every request (see Protected Routes). In framework mode loaders can run on the server, which is covered in Server Loaders, Client Loaders and Actions.

When not to use a loader

Loaders are best for the data a page cannot exist without. For secondary data (a "recommended for you" panel, a comment count) you do not want to hold up the whole navigation. You can stream that data instead, which is the topic of Streaming Data with Await and Suspense. For data that changes constantly or is shared across many screens, a cache such as TanStack Query can sit behind the loader, as covered in Revalidation and Caching.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. When does a route's loader run?

    The router calls loaders during navigation and revalidation. A simple state change that re-renders the component does not call the loader again.
  2. 2. A page matches three nested routes that each have a loader. How does the router run them?

    Nested loaders start together, which avoids a request waterfall. Total wait time is the longest single loader, not the sum.
  3. 3. How does a loader read the query string, for example ?page=2?

    params contains only the path's dynamic segments. The query string comes from the request's URL.
  4. 4. A loader cannot find the product. What is the idiomatic way to signal it?

    Throwing a Response ends the loader, skips the component, and renders the error element with the status. The component then only deals with valid data.
  5. 5. Why pass request.signal to fetch inside a loader?

    The signal is aborted when the navigation is interrupted, so abandoned requests stop instead of wasting bandwidth.

Summary

  • A loader is a function on a route object. The router calls it before rendering, and the component reads the result with useLoaderData().
  • Loaders receive { params, request }: params are path segments, and the query string comes from new URL(request.url).searchParams.
  • Loaders of all matched nested routes run in parallel, so the page waits for the slowest one rather than the sum, which avoids request waterfalls.
  • Throw a Response for expected failures like 404 and a redirect to send the user elsewhere. The component only sees valid data.
  • Data-mode loaders run in the browser: keep secrets out of them and keep server-side permission checks.
  • The runnable example is a stand-in that mirrors parallel loading, reuse and thrown responses; the real router also gives you abort signals, revalidation and nearest error boundaries.

Next: Actions and Form