Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 39 ยท Loaders and Data Loading

Loader Basics

Learn how loaders in React Router v7 framework mode fetch data before a route renders, how useLoaderData reads it, and how parallel loading avoids waterfalls.

A loader is a function exported from a route module that runs before the route renders. It fetches or computes the data the page needs, and the component reads it with a hook. On the first request the loader runs on the server and the HTML arrives complete; on later client-side navigations the router calls the loader through a data request and swaps the result in.

Because the framework itself is not available on this site, the real code is read-only. The runnable parts are small stand-ins for the ideas: a loader is just an async function that receives a request and returns data.

Your first loader

TSX
// app/routes/products.tsx
import type { Route } from "./+types/products";
import { getProducts } from "~/models/products.server";

export async function loader({}: Route.LoaderArgs) {
  const products = await getProducts();
  return { products };
}

export default function Products({ loaderData }: Route.ComponentProps) {
  return (
    <ul>
      {loaderData.products.map((p) => (
        <li key={p.id}>{p.name}</li>
      ))}
    </ul>
  );
}

Three things to notice:

  1. The component receives loaderData as a prop. The older useLoaderData() hook returns the same value anywhere inside the route.
  2. There is no useEffect, no loading flag and no empty first render. The data exists when the component runs.
  3. The file products.server.ts is a server module: the .server suffix guarantees the bundler never ships it to the browser, so database code and secrets stay private.

What loaders can return

A loader can return plain objects, arrays, strings, numbers, dates, Map, Set, BigInt, promises and more, because the data is serialized with a format richer than JSON. You can also return a Response, for example with custom headers:

TSX
import { data } from "react-router";

export async function loader() {
  const stats = await readStats();
  return data(stats, { headers: { "Cache-Control": "public, max-age=60" } });
}

data() keeps the typed payload while letting you set a status or headers (see HTTP Caching and Headers).

JS Stand-in: a router that runs a loader before rendering

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Parent and child loaders run in parallel

With nested routes, the router calls all matched loaders at the same time. A layout that loads the current user and a child that loads a project do not wait for each other. This removes the classic "fetch on mount" waterfall, where a child cannot start its request until its parent has rendered.

sequenceDiagram
  participant B as Browser
  participant R as Router
  participant L1 as root loader
  participant L2 as dashboard loader
  participant L3 as project loader
  B->>R: GET /dashboard/projects/7
  par in parallel
    R->>L1: run
    R->>L2: run
    R->>L3: run
  end
  L1-->>R: user
  L2-->>R: stats
  L3-->>R: project
  R-->>B: HTML with all three

All matched loaders start together, so the page waits only for the slowest one.

JS Stand-in: parallel loaders finish in the time of the slowest

Press Run (or Ctrl + Enter) to see the console output here.

No output.

If one loader depends on another's result, fetch inside a single loader instead, or restructure so the dependency is a URL parameter that both can read.

Loaders and the server boundary

A loader is not a public API you design: it is called by the framework. Still, the request can come from anyone, so validate input and check permissions inside the loader. Never trust params blindly (see Request and Params in Loaders).

Only the returned data is sent to the browser. Keep it small: return exactly the fields the page needs, not whole database rows with password hashes and internal notes.

TSX
const user = await db.user.findUnique({ where: { id } });
return { user: { id: user.id, name: user.name } }; // not the whole row

When there is no data

Throw instead of returning null when the thing the URL names does not exist. The route's error boundary then renders a proper 404 (see Throwing Responses and 404s):

TSX
if (!product) throw new Response("Not found", { status: 404 });

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When does a route's loader run for a client-side navigation?

    The router runs the loader first, then renders with the data.
  2. 2. What does the .server file suffix guarantee?

    The bundler refuses to include .server modules in client code.
  3. 3. Three nested routes each have a loader. How are they called?

    All matched loaders run concurrently, which avoids waterfalls.
  4. 4. Why return only some fields of a database row?

    Loader data is serialized into the HTML and data responses visible to the user.

Summary

  • A loader is an async route-module function that runs before render and returns data to the component.
  • Matched loaders run in parallel; the page waits for the slowest.
  • Put database code in .server modules and return only the fields you need.
  • Throw a Response for missing resources.

Next: Request and Params in Loaders