Skip to content
Tutorials Center
My learning

Topics

Lesson 25 of 50 ยท Data Mode

Pending and Optimistic UI

Show progress bars, pending links and saving states with useNavigation and fetcher state, and make forms feel instant with optimistic updates in React Router.

A data router does its work before it shows the next page: it runs loaders, and after a form submission it runs an action and then the loaders again. That is great for consistency, but it creates a gap. While the data is on its way, the user clicked something and nothing seems to happen. Slow networks make the gap long enough to notice and long enough to click the same link three times.

React Router closes the gap with state you can read: is a navigation in progress, where is it going, and what was submitted? In this lesson you will read that state with useNavigation and useFetcher, build a global progress indicator and pending links, and then go one step further with optimistic UI: showing the result of a mutation immediately, before the server has confirmed it. If you have not yet met loaders, actions and fetchers, read Loaders, Actions and Form and useFetcher first.

The three navigation states

useNavigation() returns an object that describes the router's current navigation. Its most important field is state, which is always one of three strings:

State Meaning
"idle" Nothing is happening. The page on screen is the current location.
"loading" Loaders are running for the next location (a link click, a redirect, or the revalidation after an action).
"submitting" A form was submitted and its action is running.
flowchart LR
    A["idle"] -->|"click a Link"| B["loading"]
    B -->|"loaders finish"| A
    A -->|"submit a Form (POST)"| C["submitting"]
    C -->|"action finishes"| B

A link goes straight to loading. A POST form passes through submitting first, then loading while the loaders revalidate.

Two more fields help. navigation.location is the location the router is heading to (it is undefined when idle). navigation.formData holds the submitted FormData (also formMethod and formAction) while a submission is in flight, and undefined otherwise.

Here is the real React Router code for a global progress indicator in a root layout (read-only, because the live editor cannot install packages):

JSX
// root-layout.jsx - React Router (read-only)
import { Outlet, useNavigation } from 'react-router';

export default function RootLayout() {
  const navigation = useNavigation();
  const isBusy = navigation.state !== 'idle';

  return (
    <div>
      <div className={isBusy ? 'progress progress-active' : 'progress'} role="progressbar" />
      <Header />
      <main style={{ opacity: isBusy ? 0.6 : 1 }}>
        <Outlet />
      </main>
    </div>
  );
}

Notice what does not happen: the old page is not replaced by a blank screen or a spinner. The current route stays visible, and you decide how to signal that something is under way, usually by dimming the content and showing a thin bar at the top.

useNavigation only works under a data router such as createBrowserRouter plus RouterProvider. Under plain <BrowserRouter> there are no loaders to wait for, and the hook throws.

Real library or stand-in? The code blocks above and below that import from react-router are the real API. The live examples use a small hand-written router built on React and location.hash that behaves like a data router in the one way this lesson needs: it keeps the old page on screen until the next page's loader has finished. It exposes a navigation object with the same state and location fields. Unlike the real router, it changes the hash immediately when you click, whereas React Router updates the address bar when the navigation completes.

A navigation state and progress bar

Click "reports" and watch three things: the state flips to loading, the link you clicked is marked as the destination, and the old page stays on screen, dimmed, until the loader finishes. If you click "team" while "reports" is still loading, the stale result is thrown away. React Router does the same: a newer navigation interrupts the older one, so you never end up on a page you did not ask for last.

The same information is available per link. NavLink passes isPending to its className, style and children functions, and it is true when that link's destination is the one being navigated to:

JSX
// nav.jsx - React Router (read-only)
import { NavLink } from 'react-router';

export function Nav() {
  return (
    <nav>
      <NavLink
        to="/reports"
        className={({ isActive, isPending }) =>
          isPending ? 'nav-link pending' : isActive ? 'nav-link active' : 'nav-link'
        }
      >
        Reports
      </NavLink>
    </nav>
  );
}

This is cheaper than reading useNavigation in every link and keeps the logic next to the markup. See Link and NavLink for the rest of the props.

Pending state for forms

A <Form> submission goes through submitting and then loading, so you can disable the button and change its label from the same useNavigation call. The formData field tells you which form is pending when a page has several:

JSX
// new-note.jsx - React Router (read-only)
import { Form, useNavigation } from 'react-router';

export default function NewNote() {
  const navigation = useNavigation();
  const isSaving =
    navigation.state === 'submitting' && navigation.formAction === '/notes/new';

  return (
    <Form method="post" action="/notes/new">
      <input name="title" required />
      <button disabled={isSaving}>{isSaving ? 'Saving...' : 'Save note'}</button>
    </Form>
  );
}

For a single form on a page, React DOM's useFormStatus (see useFormStatus and optimistic updates) is an alternative that needs no router state. useNavigation shines when the indicator lives somewhere else than the form, such as the header bar above.

Fetcher state: pending UI for one control

A navigation is global, which is wrong for a small control such as a "like" button: liking a post is not a page change and should not dim the whole screen. Fetchers have their own state with the same three values. Every fetcher exposes fetcher.state ("idle", "submitting" or "loading"), and fetcher.formData while it is submitting. To watch all fetchers at once (for example, a "saving..." badge in the header), call useFetchers() and check whether any of them is not idle.

Optimistic UI

Pending UI says "wait, I am working". Optimistic UI says "done" immediately and fixes it later if the server disagrees. It is the right choice for actions that almost always succeed (toggling a favorite, ticking a todo, reordering) and the wrong one for payments, deletions that cannot be undone, or anything with a visible server-side result such as a generated ID you must show.

React Router makes this easy because the submitted data is available: while a fetcher is submitting, fetcher.formData contains exactly what the user just sent. Derive what to show from it, and fall back to the real value from the loader when no submission is pending:

JSX
// favorite-button.jsx - React Router (read-only)
import { useFetcher } from 'react-router';

export function FavoriteButton({ post }) {
  const fetcher = useFetcher();

  // while submitting: what the user just asked for; otherwise: the loader's value
  const isFavorite = fetcher.formData
    ? fetcher.formData.get('favorite') === 'true'
    : post.isFavorite;

  return (
    <fetcher.Form method="post" action={`/posts/${post.id}/favorite`}>
      <button name="favorite" value={isFavorite ? 'false' : 'true'}>
        {isFavorite ? 'Unfavorite' : 'Favorite'}
      </button>
    </fetcher.Form>
  );
}

There is no extra state and no cleanup code. When the action finishes, the loaders revalidate (see Revalidation), fetcher.formData becomes undefined, and the component shows the loader's value. If the action failed, that value is the old one, so the interface snaps back to the truth without any rollback logic. That automatic correction is the main reason to build optimistic updates on top of router state instead of local copies.

sequenceDiagram
    participant U as User
    participant UI as Component
    participant S as Server
    U->>UI: click Favorite
    UI->>UI: show fetcher.formData value at once
    UI->>S: action request
    S-->>UI: success or failure
    UI->>UI: loaders revalidate, show real value

The optimistic value only lives while the submission is in flight. The revalidated loader data always has the last word.

The next example runs the same idea without the library: a "server" that answers after 700 ms and rejects one item.

Optimistic toggles that roll back

Tick "Read the loaders lesson" with optimistic updates on: it flips immediately and "saving..." appears for 700 ms. Turn optimistic updates off and try again: the box waits for the server. Finally tick item C: it flips, the server rejects it, and it flips back with a message. The rollback is free because the displayed value is derived from pending data plus the server value, never stored as a second copy.

Good pending-UI habits

  • Do not flash for fast responses. If a spinner appears for 80 ms it feels slower than none. Delay the indicator slightly (a CSS transition-delay is enough).
  • Keep the old content visible. Dim it instead of replacing it, so layout does not jump.
  • Prevent double submits by disabling the button while state !== "idle", but remember the server must still be safe against duplicates.
  • Show errors. An optimistic update that silently reverts is confusing; pair it with a message (see Error Boundaries and Error Elements).
  • Mind accessibility. A progress bar made of divs is invisible to screen readers; announce long waits with aria-busy or a live region.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A user submits a POST form that has an action and a loader on the next page. Which sequence of navigation.state values does the router report?

    A POST submission is submitting while the action runs, then loading while the loaders revalidate, then idle. A plain link click skips the submitting step.
  2. 2. You want a thin progress bar in the header while any navigation is in progress. Which is the simplest correct condition?

    Both loading and submitting mean work is under way. formData is only set for submissions, and location being undefined means the router is idle.
  3. 3. What does fetcher.formData contain while a fetcher submission is in flight, and why is that useful?

    formData holds the submitted values until the submission settles. Deriving the displayed value from it needs no extra state, and when it becomes undefined the loader's value shows again.
  4. 4. An optimistic favorite button used fetcher.formData to decide what to show, and the server rejected the request. What does the user see afterwards?

    The optimistic value existed only while the submission was pending. Once it ends, the component renders the loader's data, which still has the old value, so the UI corrects itself.

Summary

  • useNavigation() reports state (idle, loading, submitting), the destination location and the submitted formData; it works only in data routers.
  • The old page stays on screen while the next one loads, so pending UI means dimming, a progress bar and pending links, not blank screens.
  • NavLink passes isPending to its render props for per-link feedback.
  • Fetchers have their own state and formData, so small controls can show progress without affecting the whole page.
  • Optimistic UI derives the displayed value from fetcher.formData when present and from loader data otherwise, which gives automatic rollback on failure.
  • Use optimistic updates for likely-to-succeed actions only, and always handle and show failures.

Next: Streaming Data with Await and Suspense