Sub topic 12
Showing pending and submitting states
This chapter assumes you can define routes with createBrowserRouter, write a loader, and write an action with Form. You should also be comfortable with React hooks and conditional rendering.
Why pending state needs its own handling
With loaders and actions, the router does work before it renders the next page. A loader may take 800 ms. An action may take a second to save data. During that time the router keeps the current page on screen. If you add nothing, the user clicks a link and sees no change until the new data arrives. They may click again, or submit a form twice.
React Router tracks this work for you. You read it with the useNavigation hook and show whatever feedback you want.
The three navigation states
useNavigation returns an object that describes the navigation in progress. Its state property has one of three values.
| State | Meaning |
|---|---|
| `idle` | No navigation is in progress. |
| `loading` | Loaders are running for the next location. This also covers the revalidation that follows an action. |
| `submitting` | A `Form` was submitted with a method other than GET, and the action is running. |
The hook is read-only and applies to the whole router. It does not belong to one route. Any component rendered inside RouterProvider can call it.
A POST submission passes through submitting and then loading. After the action returns or redirects, the router runs the loaders again so the page shows fresh data. That second phase is the loading state. Your UI therefore sees submitting, then loading, then idle.
A GET form, such as a search box, skips submitting. It is a plain navigation to a new URL with a query string, so it goes straight to loading.
A global loading indicator
The most common use is a progress indicator in the root layout. The layout stays mounted across navigations, so it can react to every one of them.
import {
createBrowserRouter,
RouterProvider,
Link,
Outlet,
useLoaderData,
useNavigation,
} from "react-router-dom";
function Layout() {
const navigation = useNavigation();
const isBusy = navigation.state !== "idle";
return (
<div>
<nav>
<Link to="/">Home</Link> <Link to="/slow">Slow page</Link>
</nav>
<p role="status" aria-live="polite">
{isBusy ? "Loading..." : ""}
</p>
<main style={{ opacity: isBusy ? 0.5 : 1 }}>
<Outlet />
</main>
</div>
);
}
async function slowLoader() {
await new Promise((resolve) => setTimeout(resolve, 1000));
return { message: "Data arrived" };
}
function Slow() {
const { message } = useLoaderData();
return <h1>{message}</h1>;
}
const router = createBrowserRouter([
{
path: "/",
element: <Layout />,
children: [
{ index: true, element: <h1>Home</h1> },
{ path: "slow", element: <Slow />, loader: slowLoader },
],
},
]);
export default function App() {
return <RouterProvider router={router} />;
}Click "Slow page". The old page dims and "Loading..." appears for one second. Then the new page replaces it. The role="status" and aria-live attributes make screen readers announce the change.
The old page stays visible the whole time. The router does not render the next route until its loaders finish. This is different from a component that fetches in useEffect, which renders first and then shows a spinner. If you want the new page to appear immediately with its own placeholder, loaders are the wrong tool for that route.
Submitting state on a form
Inside a form component, use navigation.state to disable the button and change its label. This is the pattern from the actions chapter, shown here in full.
import { Form, redirect, useNavigation } from "react-router-dom";
export async function createContactAction({ request }) {
const formData = await request.formData();
await fetch("/api/contacts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name: formData.get("name") }),
});
return redirect("/contacts");
}
export function NewContact() {
const navigation = useNavigation();
const isSubmitting = navigation.state === "submitting";
return (
<Form method="post">
<input name="name" required />
<button type="submit" disabled={isSubmitting}>
{isSubmitting ? "Saving..." : "Save"}
</button>
</Form>
);
}Disabling the button prevents double submission while the action runs. Once the action redirects, the state becomes loading and the button is enabled again, but by then the router is already moving to the next page.
What else is on the navigation object
useNavigation returns more than state. These properties are populated only while a navigation is in progress.
navigation.locationis the destination. It isundefinedwhen idle.navigation.formDatais the submittedFormData, orundefinedif the navigation did not come from a form.navigation.formMethodandnavigation.formActiondescribe the submission.
The destination location lets you show pending feedback on one specific link instead of the whole page.
import { Link, useNavigation } from "react-router-dom";
export function PendingLink({ to, children }) {
const navigation = useNavigation();
const isGoingHere =
navigation.state === "loading" && navigation.location.pathname === to;
return (
<Link to={to} aria-busy={isGoingHere}>
{children}
{isGoingHere ? " (loading)" : ""}
</Link>
);
}NavLink has this built in. Its className, style, and children props accept a function that receives isPending alongside isActive.
import { NavLink } from "react-router-dom";
export function NavItem({ to, label }) {
return (
<NavLink
to={to}
className={({ isActive, isPending }) =>
isPending ? "pending" : isActive ? "active" : undefined
}
>
{label}
</NavLink>
);
}Optimistic UI from formData
Because navigation.formData holds the values the user just submitted, you can show them before the server confirms. This is called optimistic UI. The sketch below shows a pending item while the action runs.
import { Form, useLoaderData, useNavigation } from "react-router-dom";
export function Contacts() {
const contacts = useLoaderData();
const navigation = useNavigation();
const pendingName =
navigation.state === "submitting" ? navigation.formData.get("name") : null;
return (
<>
<ul>
{contacts.map((c) => (
<li key={c.id}>{c.name}</li>
))}
{pendingName && <li style={{ opacity: 0.5 }}>{pendingName}</li>}
</ul>
<Form method="post">
<input name="name" required />
<button type="submit">Add</button>
</Form>
</>
);
}If the action fails, the pending item disappears when the state returns to idle, and the error boundary or action data takes over. Never treat optimistic data as saved.
Common errors
- Checking the wrong state.
navigation.state === "submitting"is false during the redirect's loading phase. If you want "anything in progress", compare with!== "idle". - Expecting a pending indicator for a GET form. A search form with
method="get"never enterssubmitting. Check forloading. - Reading
navigation.location.pathnamewhile idle.locationisundefinedwhen idle, so guard it with a state check first, asPendingLinkdoes. - Calling
useNavigationoutside the router. The hook throws if no data router is above the component. Render the component underRouterProvider. In tests, usecreateMemoryRouter. - Using it for mutations that should not navigate. A "like" button should not make the whole page look busy.
useFetchergives you a separatefetcher.statewith the same three values, scoped to that one fetcher, and it does not changeuseNavigation.
Exercise
A user submits a POST form whose action ends with return redirect("/contacts"). List the values of navigation.state the component sees, in order, and say which one you would use to disable the submit button.
Show answer
The values are submitting while the action runs, then loading while the loaders for /contacts run, then idle. Disable the button when the state is submitting, since that is the phase where a second click could send a duplicate request. You may also disable it during loading if you want to block clicks until the new page is ready.
Exercise
Why does a search form with method="get" never show the submitting state, and which state should a "Searching..." message check instead?
Show answer
A GET submission is a normal navigation to a URL with a query string. It has no action to run, so the router goes directly to loading while loaders run. Check navigation.state === "loading", and optionally navigation.formMethod === "get" to tell it apart from a link click.