Sub topic 14
Fetchers and optimistic UI
This chapter assumes you have read the chapters on loaders, actions, and useNavigation. You should be comfortable with Form, request.formData(), and the fact that a successful action makes React Router revalidate (rerun) the loaders on the page.
Why fetchers exist
A Form submission is a navigation. The URL can change, useNavigation reports the pending state, and the whole page participates. Many interactions are not navigations. Examples are a favorite star, a "mark done" checkbox, a live search box, and a delete button in a list row. These should call a route's action or loader and leave the URL alone.
A fetcher is that tool. useFetcher returns an object that can submit to an action or call a loader without navigating. Each fetcher tracks its own state, so several can be in flight on the same page.
The fetcher object
The properties you will use most:
| Property | Meaning |
|---|---|
| `fetcher.state` | `"idle"`, `"submitting"`, or `"loading"` |
| `fetcher.formData` | The `FormData` of the current submission, or `undefined` when none is active |
| `fetcher.data` | The last value returned by the action or loader |
| `fetcher.Form` | A `Form` that submits through this fetcher |
| `fetcher.submit(...)` | Submits programmatically |
| `fetcher.load(href)` | Calls a loader without navigating |
A fetcher moves through three states for each mutation.
fetcher.formData is available during both submitting and loading. This matters for optimistic UI, described below.
A fetcher-backed button
This example adds a favorite toggle to the contact detail route from earlier chapters. The action handles the mutation. The component renders a fetcher.Form.
import { useFetcher } from "react-router";
import type { Route } from "./+types/detail";
import { getContact, updateContact } from "~/contacts.server";
export async function loader({ params }: Route.LoaderArgs) {
const contact = await getContact(params.contactId);
if (!contact) {
throw new Response("Not found", { status: 404 });
}
return { contact };
}
export async function action({ request, params }: Route.ActionArgs) {
const formData = await request.formData();
const favorite = formData.get("favorite") === "true";
await updateContact(params.contactId, { favorite });
return { ok: true };
}
function FavoriteButton({ favorite }: { favorite: boolean }) {
const fetcher = useFetcher();
return (
<fetcher.Form method="post">
<button
type="submit"
name="favorite"
value={favorite ? "false" : "true"}
aria-label={favorite ? "Remove from favorites" : "Add to favorites"}
>
{favorite ? "★" : "☆"}
</button>
</fetcher.Form>
);
}
export default function ContactDetail({ loaderData }: Route.ComponentProps) {
const { contact } = loaderData;
return (
<div>
<h1>{contact.name}</h1>
<FavoriteButton favorite={contact.favorite} />
</div>
);
}fetcher.Form has no action prop here, so it posts to the action of the route that renders it. Clicking the button does not change the URL. After the action returns, React Router reruns the loader, and contact.favorite updates.
Without further work, the star changes only after the round trip finishes. On a slow connection the button feels broken.
Making it optimistic
Optimistic UI shows the expected result immediately and lets the server confirm it afterward. With fetchers you do not store extra state. You read the pending submission from fetcher.formData and fall back to the real data when there is none.
function FavoriteButton({ favorite: serverFavorite }: { favorite: boolean }) {
const fetcher = useFetcher();
const favorite = fetcher.formData
? fetcher.formData.get("favorite") === "true"
: serverFavorite;
return (
<fetcher.Form method="post">
<button
type="submit"
name="favorite"
value={favorite ? "false" : "true"}
aria-label={favorite ? "Remove from favorites" : "Add to favorites"}
>
{favorite ? "★" : "☆"}
</button>
</fetcher.Form>
);
}The value follows the submission while it is pending. Once the fetcher returns to idle, formData is undefined again and the component shows the loader's value. That has two consequences:
- On success, the two values agree, so nothing visibly changes.
- On failure, the UI reverts to the server's value with no rollback code. If the action returns an error object, the loader data is unchanged, so the star flips back. If the action throws, the nearest error boundary renders instead.
Because formData persists through the loading phase, the optimistic value stays on screen until fresh loader data arrives. This avoids a flicker back to the old value.
Multiple fetchers on one page
Each call to useFetcher creates an independent fetcher. A list with one FavoriteButton per row therefore has one fetcher per row. Clicking one star does not put the others in a pending state. Compare this with useNavigation, which has a single global state.
If you need to read a fetcher's state from a different component, give it a key. Any component that calls useFetcher({ key: "favorite-42" }) shares that fetcher. useFetchers() returns all active fetchers, which is useful for a global "saving..." indicator.
Submitting without a form
Use fetcher.submit when the trigger is not a form, for example a checkbox that saves on change:
import { useFetcher } from "react-router";
export function DoneCheckbox({ id, done }: { id: string; done: boolean }) {
const fetcher = useFetcher();
const checked = fetcher.formData
? fetcher.formData.get("done") === "true"
: done;
return (
<input
type="checkbox"
checked={checked}
onChange={(event) =>
fetcher.submit(
{ id, done: String(event.currentTarget.checked) },
{ method: "post", action: "/tasks" },
)
}
/>
);
}Values passed to submit become form fields, so they are strings. Convert booleans and numbers on the way in and parse them in the action. Here action: "/tasks" targets another route's action explicitly.
Loading data with a fetcher
fetcher.load("/search?q=ada") calls the loader of the matching route, and the result appears in fetcher.data. The target should be a route with a loader, usually a resource route. This suits comboboxes and popovers that need data outside the page's own loader.
Common mistakes
- Reading
fetcher.dataas optimistic state.datais the action's response, so it appears after the action finishes. Usefetcher.formDatafor the in-flight value. - Forgetting that
fetcher.Formposts to the current route. If the action lives elsewhere, setaction. - Treating fetcher submissions as navigations. They do not add history entries and do not change
useNavigation().state. - Skipping validation because the UI is optimistic. The server must still check every submission. Return an error object and let the revert show the user what happened.
Exercise
A comment "like" button uses fetcher.formData to show the new count immediately. The action fails and returns { error: "Rate limited" } without throwing. What does the user see after the fetcher returns to idle, and why?
Show answer
The count returns to its previous value. After the fetcher goes idle, fetcher.formData is undefined, so the component falls back to the loader's count. The failed action changed nothing, so the loader still reports the old value. The error text is available in fetcher.data if you want to display it.
Exercise
Why does a page with a list of rows, each with its own useFetcher, not show every row as "saving" when you click one row's button?
Show answer
Each useFetcher call creates an independent fetcher with its own state, formData, and data. Only the fetcher that submitted leaves idle. useNavigation is different because it reports one page-wide state.