Sub topic 7
Loading data with loaders
This chapter assumes you know React components and props, TypeScript basics, HTTP status codes, and how routes are declared in app/routes.ts. A loader is the function a route module exports to supply data before the route renders.
What a loader does
In framework mode, a route module can export a loader function. React Router calls it on the server for the initial document request. It calls it again, through a data request, when the user navigates to the route on the client. Whatever the loader returns becomes the loaderData prop of the route's default component.
Loaders run before rendering. The component never shows a half-loaded state for its own data, and you don't need useEffect or manual loading flags.
A working loader
This route is mapped to contacts/:contactId. The loader reads the URL parameter, fetches a record, and returns it.
import { data } from "react-router";
import type { Route } from "./+types/detail";
import { getContact } from "~/contacts.server";
export async function loader({ params }: Route.LoaderArgs) {
const contact = await getContact(params.contactId);
if (!contact) {
throw data("Contact not found", { status: 404 });
}
return { contact };
}
export default function ContactDetail({ loaderData }: Route.ComponentProps) {
return <h1>{loaderData.contact.name}</h1>;
}Three points to notice:
paramsholds the dynamic segments from the route path. Hereparams.contactIdcomes from:contactId.Route.LoaderArgsandRoute.ComponentPropsare generated types. The type ofloaderData.contactfollows from what the loader returns.- Throwing
data(...)with a 404 stops the loader. React Router then renders the nearestErrorBoundaryinstead of the component.
What a loader receives
| Argument | Contents |
|---|---|
| `params` | Dynamic path segments such as `contactId` |
| `request` | A standard Fetch `Request`, which gives you the URL, headers, and cookies |
To read a query string, build a URL from the request:
export async function loader({ request }: Route.LoaderArgs) {
const url = new URL(request.url);
const q = url.searchParams.get("q") ?? "";
return { q };
}Nested routes load in parallel
When a URL matches nested routes, such as a layout and a child, React Router runs every matched loader at the same time. A layout's loader doesn't wait for its child's. Each component receives only its own route's loaderData.
Common errors
- Returning non-serializable values. Data sent to the browser must be serializable. Plain objects, arrays, strings, numbers, dates, and promises work. Class instances with methods and functions do not.
- Leaking secrets. The loader's return value is sent to the client. Return only the fields the UI needs, not a whole database row that includes private columns.
- Expecting
loaderin the browser bundle. The framework removes server loaders from client code. Helpers imported only by the loader should live in.server.tsfiles so they stay out of the client bundle. - Returning an error for a missing record. Returning
nullforces every component to handle it. Throw a 404 response instead.
Exercise
A loader for the route products/:id must read a ?currency= query parameter and return a 404 if the product does not exist. Which two arguments or tools does it use, and how does it signal the 404?
Show answer
It uses params.id to find the product and new URL(request.url).searchParams.get("currency") to read the query string. For a missing product it throws data("Product not found", { status: 404 }), which sends control to the nearest ErrorBoundary.