Sub topic 12
Showing pending state with useNavigation
This chapter assumes you can write a route module with a loader and an action, and that you know React hooks and the HTML form basics from earlier chapters. It covers how to show that a navigation or a form submission is in progress, and where this approach stops working.
Why pending state matters
In framework mode, a link click or form submit triggers work before the screen changes. The router may call loaders on the server, run an action, and then revalidate data. During that time the current page stays on screen. Without feedback, the user sees nothing happen and may click again.
React Router exposes this in-flight work through the useNavigation hook. It describes the one navigation that is currently happening. You read it and render something different, such as a disabled button or a progress bar.
The navigation object
useNavigation() returns an object. These are its main fields.
| Field | Meaning |
|---|---|
| `state` | `"idle"`, `"loading"`, or `"submitting"` |
| `location` | The destination URL while a navigation is in flight. It is `undefined` when idle. |
| `formMethod` | The HTTP method of the submission, such as `"POST"`. `undefined` for plain link navigations. |
| `formAction` | The URL the form is submitting to |
| `formData` | The submitted `FormData`, available during the submission |
The three states follow a fixed lifecycle.
idlemeans nothing is in flight.loadingmeans the router is fetching loader data for the next location. This is also the state after an action finishes, while the router follows a redirect or revalidates.submittingmeans an action is running because of a non-GET form submission.
A GET form, such as a search box, never enters submitting. It is a plain navigation with search params, so it goes straight to loading.
Disabling a submit button
The most common use is the form from the actions chapter. Compare navigation.state to "submitting" and change the button.
import { Form, data, redirect, useNavigation } from "react-router";
import type { Route } from "./+types/new";
import { createContact } from "~/contacts.server";
export async function action({ request }: Route.ActionArgs) {
const formData = await request.formData();
const name = String(formData.get("name") ?? "").trim();
if (!name) {
return data({ error: "Name is required" }, { status: 400 });
}
const contact = await createContact({ name });
return redirect(`/contacts/${contact.id}`);
}
export default function NewContact({ actionData }: Route.ComponentProps) {
const navigation = useNavigation();
const saving = navigation.state === "submitting";
return (
<Form method="post">
<input name="name" />
{actionData?.error ? <p role="alert">{actionData.error}</p> : null}
<button type="submit" disabled={saving}>
{saving ? "Saving..." : "Save"}
</button>
</Form>
);
}The button is disabled only while the action runs. When the action returns a redirect, the state moves to loading while the router fetches the detail page. The new page then replaces this one, so the form disappears. If the action returns a 400 instead, the state returns to idle and actionData holds the error.
A global progress indicator
A route may want to show that any navigation is happening, not just its own form. Put the hook in a component that renders on every page, usually root.tsx or a layout route.
import { Outlet, useNavigation } from "react-router";
export default function App() {
const navigation = useNavigation();
const busy = navigation.state !== "idle";
return (
<>
<div
role="progressbar"
aria-label="Loading"
aria-hidden={!busy}
style={{
height: 3,
background: "royalblue",
opacity: busy ? 1 : 0,
transition: "opacity 200ms 150ms",
}}
/>
<Outlet />
</>
);
}The 150ms transition delay is deliberate. Fast navigations finish before the bar becomes visible, so users do not see a flicker. Slow ones show the bar.
Telling which navigation is pending
navigation.state alone cannot distinguish a click on one link from a click on another. Use navigation.location to compare the destination.
import { NavLink, useNavigation } from "react-router";
export function ContactLink({ id, name }: { id: string; name: string }) {
const navigation = useNavigation();
const target = `/contacts/${id}`;
const pending =
navigation.state === "loading" &&
navigation.location?.pathname === target;
return (
<NavLink to={target} style={{ opacity: pending ? 0.5 : 1 }}>
{name}
</NavLink>
);
}NavLink also provides this directly. Its className and style props accept a function that receives isPending, isActive, and isTransitioning. Prefer isPending for per-link styling because it needs no hook and matches only that link.
import { NavLink } from "react-router";
export function SideLink({ to, label }: { to: string; label: string }) {
return (
<NavLink
to={to}
className={({ isActive, isPending }) =>
isPending ? "pending" : isActive ? "active" : ""
}
>
{label}
</NavLink>
);
}Reading submitted data during a submission
While an action runs, navigation.formData holds what the user sent. You can show it right away, before the server responds. This is a simple form of optimistic UI for a navigation that goes through a Form.
import { useNavigation } from "react-router";
export function PendingName() {
const navigation = useNavigation();
const submitted = navigation.formData?.get("name");
return submitted ? <p>Saving {String(submitted)}...</p> : null;
}formData is undefined when idle and for GET navigations that are not form submissions.
Edge cases and gotchas
- One navigation at a time.
useNavigationreflects only the current navigation. If the user clicks a second link, the first is cancelled and the hook now describes the second. - Fetchers are separate. A
useFetchersubmission does not changeuseNavigation. Fetchers carry their ownstate. Use the fetcher for pending UI on fetcher-driven mutations, covered in the next chapter. - Revalidation after a fetcher action is not a navigation. The page may reload data without
navigation.stateleavingidle. - GET forms.
formMethodis"GET"and the state isloading, notsubmitting. - Server rendering. On the first page load there is no client navigation. The hook reports
idleduring the server render and after hydration. - Redirects. Between the action finishing and the next page rendering, the state is
loading. If you disable a button only onsubmitting, it becomes clickable again for that short time. Checknavigation.state !== "idle"when you want it disabled through the redirect. - Hide the form data from other forms. If a page has several forms, check
navigation.formActionor a hiddenintentfield so one form's pending state does not affect another.
Choosing between useNavigation and a fetcher
| Situation | Use |
|---|---|
| A form that moves the user to another page | `useNavigation` |
| A global loading bar | `useNavigation` |
| Per-link pending style | `NavLink` `isPending` |
| A like button or inline edit that stays on the page | `useFetcher` |
Exercise
A "Save" button is disabled only when navigation.state === "submitting". Users report they can double-click it and create two contacts. What is one reason this happens, and what condition would close the gap that exists after the action returns a redirect?
Show answer
Between the action finishing and the redirect target rendering, the state is "loading", so the button becomes enabled again during that window. Disable it when navigation.state !== "idle". The button also needs a server-side guard, because the client check does not prevent duplicate requests from other sources.
Exercise
A sidebar has 20 NavLink items. You want only the link the user just clicked to look dimmed while its page loads. Which approach avoids calling useNavigation in every link, and which flag does it use?
Show answer
Pass a function to className or style on NavLink and read the isPending flag. It is true only for the link whose destination is currently loading.
Exercise
A search box uses <Form method="get">. During a search, which navigation.state value do you see, and is navigation.formData useful for showing the submitted text?
Show answer
The state is "loading", because a GET form is a navigation with search params, not an action submission. formData is available for GET form submissions, but the query is also in navigation.location.search, so either source works for showing the pending text.