Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 50 ยท Data Mode

useFetcher and Inline Mutations

Use useFetcher to submit forms and load data without navigating: fetcher.Form, fetcher.submit, fetcher.load, optimistic UI from formData and concurrent mutations.

Every form you have seen so far has been a navigation. Pressing the button submits, the router runs an action, the URL may change, and the whole page revalidates. That is the right model for "create a note" or "sign in". But think about a star button on a list item, a "mark as done" checkbox, a "like" counter, or a search box that shows suggestions. These actions should not move the user anywhere. They should not add a history entry. And five of them may be in flight at the same time.

For those cases React Router offers the fetcher. A fetcher is a way to talk to a route's action or loader without navigating. It has its own state, its own pending flag and its own data, separate from the page. In this lesson you will learn the three ways to use it (fetcher.Form, fetcher.submit and fetcher.load), build an optimistic star button, and see why many fetchers can run side by side.

You should know loaders and actions first. Fetchers reuse both.

Compare what happens in each case.

Navigation (<Form>, <Link>, navigate) Fetcher
Changes the URL Yes No
Adds a history entry Yes (or replaces one) No
Pending state lives in useNavigation(), one for the whole page fetcher.state, one per fetcher
How many at once One: a new navigation cancels the old one As many as you create
After an action Loaders revalidate Loaders revalidate
Typical use Pages, creating records, sign in Toggles, inline edits, deletes, suggestions

A fetcher does revalidate loaders after its action finishes, so the page still reflects the new data. What it skips is the navigation.

stateDiagram-v2
  [*] --> idle
  idle --> submitting : fetcher.submit or fetcher.Form
  submitting --> loading : action done, loaders revalidating
  loading --> idle : fresh data arrived
  idle --> loading : fetcher.load

A fetcher rests in "idle". Submitting runs the action, then loading revalidates the page's data.

The three ways to use a fetcher

You get a fetcher from the useFetcher() hook. Each call returns an independent fetcher. This is the real React Router API, shown read-only:

JSX
// Real React Router (data mode), read-only
import { useFetcher } from 'react-router';

function StarButton({ note }) {
  const fetcher = useFetcher();

  return (
    <fetcher.Form method="post" action="/notes/star">
      <input type="hidden" name="id" value={note.id} />
      <input type="hidden" name="starred" value={String(!note.starred)} />
      <button type="submit">{note.starred ? 'Unstar' : 'Star'}</button>
    </fetcher.Form>
  );
}

1. fetcher.Form works like <Form> but never navigates. It submits to the route's action (here /notes/star, a route that has an action and usually no UI). Without an action prop, it submits to the route that renders it, just like <Form>.

2. fetcher.submit(data, options) is the imperative version, for things that are not forms, such as a checkbox change or a drag and drop:

JSX
// Real React Router, read-only
fetcher.submit(
  { id: note.id, done: event.target.checked },
  { method: 'post', action: '/notes/done' }
);

// JSON instead of form fields:
fetcher.submit({ id: note.id }, { method: 'delete', action: '/notes/remove', encType: 'application/json' });

With encType: 'application/json' the action reads the body with await request.json() instead of request.formData(). Plain objects given without an encType arrive as form data.

3. fetcher.load(href) calls a route's loader without navigating, and puts the result in fetcher.data. It is the tool for data that is not part of the page URL: a combobox of suggestions, a popover with details, the next page of an infinite list.

JSX
// Real React Router, read-only
function CitySearch() {
  const fetcher = useFetcher();

  return (
    <div>
      <input
        type="search"
        onChange={(event) => fetcher.load('/cities?q=' + encodeURIComponent(event.target.value))}
      />
      {fetcher.state === 'loading' && <p>Searching...</p>}
      <ul>
        {(fetcher.data ?? []).map((city) => <li key={city}>{city}</li>)}
      </ul>
    </div>
  );
}

The /cities route has a loader that reads new URL(request.url).searchParams.get('q'). If the user types again before the previous load finished, the router cancels the old load, so slow responses cannot overwrite newer ones. For an index route (a route with index: true), add ?index to the href so that the router calls the index route's loader and not its parent's.

What a fetcher gives you

Property Meaning
fetcher.state 'idle', 'submitting' (the action is running) or 'loading' (a loader is running)
fetcher.data The value returned by the last finished action or loader, or undefined
fetcher.formData The FormData being submitted right now, or undefined when idle
fetcher.formMethod, fetcher.formAction The method and action of the submission in flight
fetcher.Form, fetcher.submit, fetcher.load The three ways to start work
fetcher.key An identifier; pass useFetcher({ key: 'cart' }) in two components to share one fetcher

Two details matter in practice. First, fetcher.data sticks around until the next submission, so a stale "Saved" message can linger. Show it only together with fetcher.state === 'idle', or reset it with a new submission. Second, fetcher.formData exists only while the submission is in flight, and that fact powers optimistic UI.

Optimistic UI

The star button above is slow: the user clicks, the network call takes half a second, and the star finally flips. With optimistic UI you show the expected result immediately and let the server confirm it later. Fetchers make this almost free because fetcher.formData tells you what the user just asked for:

JSX
// Real React Router, read-only
function StarButton({ note }) {
  const fetcher = useFetcher();

  const starred = fetcher.formData
    ? fetcher.formData.get('starred') === 'true' // what the user asked for
    : note.starred;                              // what the server knows

  return (
    <fetcher.Form method="post" action="/notes/star">
      <input type="hidden" name="id" value={note.id} />
      <input type="hidden" name="starred" value={String(!starred)} />
      <button aria-label={starred ? 'Unstar' : 'Star'}>{starred ? 'โ˜…' : 'โ˜†'}</button>
    </fetcher.Form>
  );
}
sequenceDiagram
  participant U as User
  participant UI as Star button
  participant F as Fetcher
  participant S as Action
  U->>UI: clicks
  UI->>F: submit starred=true
  F-->>UI: formData present, show filled star now
  F->>S: run the action
  S-->>F: ok, or an error
  F-->>UI: idle, formData gone, loader data decides

While the request is in flight the button reads the user's intent from formData. When it finishes, real data takes over.

The beauty is the rollback. When the fetcher goes back to idle, formData disappears and the component reads note.starred from the loader data again. If the action succeeded, the revalidated loader already says true. If it failed, the loader still says false, so the star flips back by itself, and you only need to show an error message. No manual undo code. The fuller treatment is in Pending and Optimistic UI.

Try it: concurrent optimistic stars

The stand-in below implements useFetcher with the same shape: state, formData, data, Form and submit. Each todo row creates its own fetcher. The "action" waits 600 ms to imitate a network call, and the third row is built to fail so that you can watch the rollback. After a successful action, the stand-in "revalidates" by reloading the list.

Try this: click the stars of rows 1 and 2 quickly, one after the other. Both flip at once and both show submitting: they are independent. Then click row 3: it flips, stays flipped for a moment, then flips back and shows the error. Notice that the URL hash never changes, because a fetcher does not navigate.

Independent fetchers with optimistic stars

What is real here? The shape of the hook and the optimistic expression fetcher.formData ? ... : todo.starred are exactly what you would write. The action is the same kind of function you would pass to a route. The hook itself, the revalidate function and the in-memory database are the stand-in; the real router also cancels stale requests, queues revalidations so that several finished fetchers trigger one reload, and handles redirects returned by the action.

Search suggestions with fetcher.load

fetcher.load is the mirror image: it runs a loader and keeps the page where it is. This stand-in calls a loader function with a request-like object that has a url, the same way the real router would. Type a few letters of a country name. Each keystroke starts a load, and only the result of the latest keystroke is shown.

fetcher.load for live suggestions

Typing ge lists Germany and Georgia; ja lists Japan and Jamaica; k lists Kenya. If you type quickly, the list always matches the final text, because stale results are dropped. The real fetcher goes one step further and aborts the old request through request.signal, as described in Loaders.

Many fetchers at once

Because every useFetcher() is independent, a list of 100 rows can have 100 fetchers, each with its own state. Deleting three rows quickly starts three requests that run side by side, and each row can show its own spinner. That is not possible with a single useNavigation, which only describes the one current navigation.

When you need an overview, such as a "Saving 3 changes..." banner, use useFetchers(). It returns every active fetcher, and you can filter by state or formAction:

JSX
// Real React Router, read-only
import { useFetchers } from 'react-router';

function SavingBanner() {
  const fetchers = useFetchers();
  const saving = fetchers.filter((f) => f.state !== 'idle').length;
  return saving > 0 ? <p>Saving {saving} change(s)...</p> : null;
}

If two components should talk to the same fetcher, for example a cart button and a cart badge, give both the same key: useFetcher({ key: 'cart' }).

When to use which

  • <Form> and navigation when the result is a new page or a new URL: create, sign in, search that should be bookmarkable.
  • fetcher.Form or fetcher.submit when the user stays where they are: toggles, inline edits, delete buttons, adding to a cart.
  • fetcher.load for data that supports one widget and does not belong in the URL: suggestions, popovers, "load more".
  • Plain fetch in an effect only when the result has nothing to do with route data, because the router cannot revalidate or cancel it.

A fetcher is automatically cleaned up when its component unmounts, and if its action returns a redirect, that redirect does navigate. You do not need to cancel fetchers by hand.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main difference between <Form> and fetcher.Form?

    Both run a route action. A navigation changes the URL and is tracked by useNavigation, while a fetcher stays on the page and has its own state.
  2. 2. How do you build an optimistic UI with a fetcher?

    formData exists only during the submission. When the fetcher returns to idle, the real loader data takes over, so a failed request rolls back automatically.
  3. 3. Which call runs a route's loader without navigating?

    fetcher.load calls the loader of the route at that URL and puts the result in fetcher.data. The page and URL stay as they are.
  4. 4. Five rows each call useFetcher() and the user clicks all five buttons quickly. What happens?

    Every useFetcher() call is independent, unlike navigation, where a new one cancels the old one. useFetchers() gives you an overview of them all.

Summary

  • A fetcher talks to a route's action or loader without navigating: no URL change, no history entry, and its own state, data and formData.
  • Start work with fetcher.Form, fetcher.submit(data, options) or fetcher.load(href).
  • After a fetcher's action finishes, the page's loaders revalidate, so the screen stays in sync.
  • Read fetcher.formData to show the expected result at once (optimistic UI). When the fetcher is idle again, loader data decides, which rolls failures back automatically.
  • Every useFetcher() is independent, so many mutations can run at the same time. useFetchers() lists them.
  • The runnable examples are stand-ins with the same API shape; the real router adds request cancellation, deduplicated revalidation and redirect handling.

Next: Pending and Optimistic UI