Sub topic 18
Client loaders and hydration fallbacks
This chapter assumes you know how server loader and action functions work in framework mode, how route modules are wired in app/routes.ts, and the basics of localStorage and Map. It covers the browser-side counterparts, clientLoader and clientAction, and the HydrateFallback export that renders while a client loader runs on first load.
Why run loaders in the browser
A server loader always runs on the server. On a client-side navigation, React Router sends a fetch request to the server and waits for the result. That is the right default, but three cases call for browser-side code:
- Caching. You want to skip the network round trip for data you already fetched.
- Browser-only data. The data lives in
localStorage,IndexedDB, or a browser API that the server cannot reach. - Static hosting. You deploy with
ssr: falseand have no server to run aloaderon.
clientLoader and clientAction are route module exports that run only in the browser.
How the two loaders interact
If a route exports both loader and clientLoader, the client loader takes over on client-side navigations. React Router gives it a serverLoader function. Calling serverLoader() makes the network request to your server loader. If you never call it, no request is made.
Caching server data with clientLoader
This route keeps fetched contacts in a module-level Map. The first visit to a contact calls the server. Later visits in the same browser session return the cached value.
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 };
}
const cache = new Map<string, Awaited<ReturnType<typeof loader>>>();
export async function clientLoader({
params,
serverLoader,
}: Route.ClientLoaderArgs) {
const cached = cache.get(params.contactId);
if (cached) return cached;
const result = await serverLoader();
cache.set(params.contactId, result);
return result;
}
export async function clientAction({
params,
serverAction,
}: Route.ClientActionArgs) {
cache.delete(params.contactId);
return serverAction();
}
export default function ContactDetail({ loaderData }: Route.ComponentProps) {
return <h1>{loaderData.contact.name}</h1>;
}The import of ~/contacts.server is safe here. The build removes the server loader from the browser bundle, so the .server module never reaches the client.
A cache needs an invalidation rule. The clientAction above deletes the entry before forwarding the mutation, so the next visit refetches. Without it, users would see stale data after editing a contact. When a route has a clientAction, React Router revalidates loaders afterward as usual. That revalidation calls clientLoader, and the cache is already cleared by then.
The first load skips clientLoader by default
On the initial document request, the server runs loader, renders HTML, and the browser hydrates with that data. clientLoader does not run, because the data is already present. This surprises people who put required logic in clientLoader, such as reading localStorage. It silently never executes on the first page view.
To force it, set the hydrate property:
import type { Route } from "./+types/draft";
type Draft = { title: string };
export async function clientLoader() {
const raw = localStorage.getItem("draft");
const draft: Draft | null = raw ? (JSON.parse(raw) as Draft) : null;
return { draft };
}
clientLoader.hydrate = true as const;
export function HydrateFallback() {
return <p>Loading your draft...</p>;
}
export default function DraftPage({ loaderData }: Route.ComponentProps) {
return <h1>{loaderData.draft?.title ?? "No draft yet"}</h1>;
}Two details matter here:
as constnarrows the property to the literaltrue. Generated route types use it to know the component only renders after the client loader has finished.HydrateFallbackis required in practice. Withhydrate = true, the server cannot render the real component because the data is not ready. It rendersHydrateFallbackinto the HTML instead, and the browser swaps in the component onceclientLoaderresolves.
Because HydrateFallback renders on the server, it must not touch window or localStorage. Keep it to static markup.
Where each export runs
| Export | Initial document load | Client-side navigation |
|---|---|---|
| `loader` | Server | Server, via `fetch` (unless `clientLoader` skips it) |
| `clientLoader` | Browser, only if `hydrate = true` | Browser |
| `action` | Server | Server, via `fetch` |
| `clientAction` | Not applicable | Browser |
| `HydrateFallback` | Server render, then browser | Not used |
SPA mode: client loaders only
With ssr: false in react-router.config.ts, the build produces static HTML with no server. Route modules cannot export loader or action. The build fails if they do. Use clientLoader and clientAction instead, and call your API with fetch.
import type { Config } from "@react-router/dev/config";
export default {
ssr: false,
} satisfies Config;In this mode, the build prerenders only the root route into index.html. Export HydrateFallback from root.tsx to control what users see before the first clientLoader finishes. A route's clientLoader runs on first load in SPA mode, even without hydrate, because no server data exists.
Common mistakes
- Putting browser-only code in
loader.localStorageis undefined on the server and throws. Move it toclientLoader. - Expecting
clientLoaderon first load. AddclientLoader.hydrate = true as constand aHydrateFallback. - Reading
windowinHydrateFallback. It renders on the server first. - Caching without invalidation. Clear or update the cache in
clientAction, or users see stale data. - Forgetting
serverLoader(). If a route has both loaders and the client one never calls it, the server loader is never used on navigations.
Exercise
A route exports loader and a clientLoader that reads a theme from localStorage. Users report that the saved theme is ignored when they open the page directly by URL, but works when they click a link to it. What causes this, and what two changes fix it?
Show answer
On a direct document load, the server runs loader and the browser hydrates with that data, so clientLoader is skipped. On a link click, the client-side navigation runs clientLoader. Fix it by setting clientLoader.hydrate = true as const and exporting a HydrateFallback that renders static markup, so the server has something to render until clientLoader finishes in the browser.
Exercise
You deploy with ssr: false. A teammate adds export async function loader() to a route. What happens, and what should they export instead?
Show answer
The build fails, because SPA mode does not allow server loader or action exports. They should export clientLoader (and clientAction for mutations) and fetch data from an API in the browser.