Sub topic 7
Loading data with loaders
This chapter covers how a route module loads data on the server with a loader, how that data reaches your component, and the mistakes that most often cause trouble. It assumes you know React components and hooks, TypeScript basics, and HTTP status codes. It also assumes you have a project with a working app/routes.ts, as in the earlier chapters.
What a loader is
A loader is an async function exported from a route module under the name loader. React Router calls it before it renders the route. The value it returns becomes the route's data.
Loaders replace the common pattern of rendering a component, starting a useEffect, and then showing a spinner while a fetch runs. With a loader, the data is ready when the component renders. On the first page load, the server runs the loader and puts the data in the HTML. On later client-side navigations, the browser asks the server to run the loader and receives the result.
Loaders are for reading data. Changing data is the job of actions, covered in the next chapters.
A first loader
This route module loads one contact by the :contactId URL parameter.
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 things happen here:
params.contactIdcomes from the:contactIdsegment inroutes/contacts/detail.tsx's path.- If no contact exists, the loader throws a 404 response. Control passes to the nearest error boundary, so the component never renders with missing data.
- Otherwise, the returned object arrives in the component as the
loaderDataprop.
What a loader receives
The loader gets one argument with these useful properties.
| Property | What it holds |
|---|---|
| `params` | URL parameters such as `contactId`, as strings |
| `request` | A standard Web `Request` for the current URL |
| `context` | Values supplied by your server adapter, if you set any up |
Because request is a standard Request, you can read the query string with the URL class. This loader filters a list by a q search parameter.
import type { Route } from "./+types/list";
import { searchContacts } from "~/contacts.server";
export async function loader({ request }: Route.LoaderArgs) {
const url = new URL(request.url);
const q = url.searchParams.get("q") ?? "";
const contacts = await searchContacts(q);
return { contacts, q };
}
export default function ContactList({ loaderData }: Route.ComponentProps) {
return (
<ul>
{loaderData.contacts.map((c) => (
<li key={c.id}>{c.name}</li>
))}
</ul>
);
}Params are always strings. Convert and check them yourself if you need a number.
How loaders run for nested routes
When the URL matches several nested routes, every matched route with a loader runs, and they run in parallel. A layout's loader and its child's loader start at the same time, so you do not get a waterfall where the child waits for the parent.
Each route's component receives only its own loaderData. A child cannot read the parent loader's return value through props. If a child needs the same value, load it again in the child, or read the parent's data with useRouteLoaderData, which takes the parent's route ID.
On client-side navigation, React Router reruns loaders only when needed. Moving between /contacts/1 and /contacts/2 reruns the detail loader because the params changed. A layout loader whose inputs did not change is rerun after form submissions, but not on every link click.
The diagram shows the order of events on a client navigation.
While this request is in flight, the old page stays on screen. You can show a pending indicator with useNavigation, which a later chapter covers.
What you can return
A loader can return a plain object, which is the most common choice. Beyond JSON-like values, React Router also serializes Date, Map, Set, BigInt, and promises. Functions and class instances with methods do not survive the trip, so return plain data.
To set a status or headers, return data(value, init):
import { data } from "react-router";
import type { Route } from "./+types/stats";
import { getStats } from "~/stats.server";
export async function loader(_: Route.LoaderArgs) {
const stats = await getStats();
return data(stats, {
headers: { "Cache-Control": "max-age=60" },
});
}To send the user elsewhere, return or throw a redirect:
import { redirect } from "react-router";
import type { Route } from "./+types/old";
export async function loader({ params }: Route.LoaderArgs) {
return redirect(`/contacts/${params.contactId}`);
}Common errors
Importing server-only code is fine, but leaking secrets is not. Code inside a loader is removed from the browser bundle. Anything the loader imports is also removed, as long as nothing else in the module uses it. If your component uses an import too, it ships to the client. Keep database and secret-handling code in .server.ts files, which the build refuses to bundle for the browser.
Returning too much. Whatever you return is sent to the browser and visible in the HTML. If you load a user record with a password hash, return only the fields the page needs.
Treating thrown values as bugs. Throwing data(...) or redirect(...) is the intended way to stop early. Only unexpected exceptions, such as a database being down, are real bugs. Both reach an error boundary, but thrown responses carry a status you choose.
Forgetting that params are strings. params.contactId is "7", not 7. A strict comparison with a number fails silently.
Fetching in the component as well. If a component calls fetch in useEffect for data a loader could provide, you lose server rendering of that data and add a loading flash.
Expecting loaderData to be state. It is a snapshot for the current navigation. When it changes, the component rerenders with the new value. Do not copy it into useState unless you also handle updates, or the copy goes stale.
Decision criteria
- Use a loader when the data is needed to render the page and depends on the URL.
- Use a fetcher when you load or save data without navigating, such as a small widget.
- Use a
clientLoaderwhen the data must come from the browser, for example fromlocalStorage. A later chapter covers it.
Exercise
A route at /contacts/:contactId has a loader that calls getContact(params.contactId). The contact does not exist. Which should the loader do, and what happens next? Why is returning null a weaker choice?
Show answer
It should throw data("Contact not found", { status: 404 }). React Router stops rendering the route component and shows the nearest ErrorBoundary with a 404 response. Returning null makes the component handle a missing value, and the response status stays 200, which is wrong for a missing page and misleads browsers and search engines.
Exercise
A parent layout route and its child route each export a loader that makes a 200 ms database query. Roughly how long does the data take to load on a fresh navigation, and why?
Show answer
About 200 ms. Matched loaders run in parallel, so the child's loader does not wait for the parent's.