Sub topic 17
Client loaders, resource routes, and rendering strategies
This chapter assumes you know route modules, server loader and action functions, and the Route types that React Router generates. It covers three topics: running data code in the browser, serving non-HTML responses, and choosing how the app is rendered.
Client loaders and hydration fallbacks
A clientLoader runs in the browser. On client-side navigations it runs instead of the server loader unless you call serverLoader() inside it. This lets you cache results, read from localStorage, or call an API directly from the browser.
import type { Route } from "./+types/detail";
export async function loader({ params }: Route.LoaderArgs) {
return { name: `Server contact ${params.contactId}` };
}
export async function clientLoader({
params,
serverLoader,
}: Route.ClientLoaderArgs) {
const cached = sessionStorage.getItem(`contact:${params.contactId}`);
if (cached) return JSON.parse(cached) as { name: string };
const fresh = await serverLoader();
sessionStorage.setItem(`contact:${params.contactId}`, JSON.stringify(fresh));
return fresh;
}
export default function ContactDetail({ loaderData }: Route.ComponentProps) {
return <h1>{loaderData.name}</h1>;
}By default, clientLoader does not run during the first server render. If you want it to run on the initial page load too, set clientLoader.hydrate = true. The server cannot supply that data, so you must also export a HydrateFallback. React Router renders it until the client loader finishes.
clientLoader.hydrate = true as const;
export function HydrateFallback() {
return <p>Loading contact...</p>;
}clientAction works the same way for mutations. It runs in the browser and can call serverAction() to reach the server action.
Resource routes
A resource route is a route module with no default component export. It returns a Response or plain data, so you can use it for JSON APIs, images, CSV downloads, or webhooks. A loader handles GET requests. An action handles POST, PUT, PATCH, and DELETE.
import type { Route } from "./+types/contacts-export";
import { listContacts } from "~/contacts.server";
export async function loader(_: Route.LoaderArgs) {
const contacts = await listContacts();
const csv = ["name", ...contacts.map((c) => c.name)].join("\n");
return new Response(csv, {
headers: {
"Content-Type": "text/csv",
"Content-Disposition": 'attachment; filename="contacts.csv"',
},
});
}Register it in app/routes.ts like any other route: route("contacts.csv", "routes/contacts-export.ts"). Link to it with a plain <a href> or use reloadDocument on a Link, because client-side navigation would try to render a component.
Choosing SSR, prerendering, or SPA mode
Set the strategy in react-router.config.ts.
| Strategy | Config | HTML produced | Server needed at runtime |
|---|---|---|---|
| SSR | `ssr: true` | On every request | Yes |
| Prerendering | `prerender: [...]` | At build time for listed paths | Only if `ssr: true` also |
| SPA mode | `ssr: false` | One `index.html` shell at build time | No |
import type { Config } from "@react-router/dev/config";
export default {
ssr: false,
prerender: ["/", "/about"],
} satisfies Config;With ssr: false, server loader and action exports are not allowed, because there is no server. Use clientLoader and clientAction instead, with a HydrateFallback on the root route for the initial shell.
Exercise
You set ssr: false and a route still exports a server loader. What goes wrong, and how do you fix it?
Show answer
The build fails or the loader is unusable, because SPA mode has no runtime server. Replace loader with clientLoader, and export a HydrateFallback so the initial shell renders while data loads.
Exercise
Why does a CSV download route need reloadDocument or a plain <a> link?
Show answer
A resource route has no component. Client-side navigation expects a component to render, so a full document request is needed to receive the file.