# React Router framework mode

FUNSTACK UI needs no setup for React Router in framework mode. Framework mode without React Server Components has no [Server Functions](nextjs.md#server-functions): the server code that changes data is a route action, which the browser reaches through a form, a fetcher or `fetch`. This page covers how that meets the library's [action props](action-props.md). The numbers below were measured in a test app with React Router 8.5.3 (framework mode, `ssr: true`), React 19.3.1 and `@funstack/ui` 0.1.0-beta.2, where every loader and action took 300 to 700 ms.

The page is written for React Router 8. Everything on it also works on React Router 7.15 and later (it was first measured on 7.18.7, with the same behaviour). The differences are in middleware: React Router 7 runs it only behind a future flag, and its default `entry.server.tsx` gives `loadContext` a different type. The [CSP nonce](#csp-nonce) section says what to change.

React Router terms used on this page:

- A loader is the function a route module exports to read its data on the server; the component reads the result as `loaderData`.
- A route action is the function a route module exports as `action` to handle a non-GET request (a form post). It is React Router's, and unrelated to the library's action props.
- Revalidation is React Router calling the loaders of the page again so that it shows fresh data.
- A fetcher (`useFetcher()`) calls a route action or a loader without navigating, and keeps the result in `fetcher.data`.
- A resource route is a route module with no component: its loader or action answers a request with data, for `fetch`.

React Router's experimental RSC mode does have Server Functions; for it, read [Server Components](server-components.md) instead of this page.

## <a id="use-transitions"></a>`useTransitions`: a trade-off

React Router's `useTransitions` prop decides whether the router uses React transitions, and it has three settings. The library works with each of them. They differ in what a pending library action holds, and in whether React Router's own hooks read correctly while one is pending.

```tsx
// app/entry.client.tsx
import { startTransition, StrictMode } from "react";
import { hydrateRoot } from "react-dom/client";
import { HydratedRouter } from "react-router/dom";

startTransition(() => {
  hydrateRoot(
    document,
    <StrictMode>
      <HydratedRouter useTransitions />   {/* or useTransitions={false}, or leave it out */}
    </StrictMode>,
  );
});
```

What each setting does, from the React Router 8.5.3 source and its [React Transitions page](https://reactrouter.com/explanation/react-transitions) (on React Router 7 the prop is stable from 7.15, `unstable_useTransitions` from 7.10):

- **Left out (the default):** the router hands every state change (a navigation's new route, a fetcher's state) to React inside `startTransition`. A pending library action holds them: the new route renders, and `fetcher.state` and `useNavigation()` change, only when the action has settled. The navigation itself is not one long transition, so it holds nothing else while its loaders run.
- **`true`:** the same, and in addition each `<Link>` and `<Form>` navigation runs in a transition that lasts until the navigation is complete, and the router state is passed through `useOptimistic`, so `useNavigation()`, `useFetcher()`, `useRevalidator()` and `useActionData()` report the navigation in progress while an action is pending.
- **`false`:** no transitions: the router sets its state with a plain `setState`. A pending library action holds neither the new route nor the router's hooks. The cost is that React's transition behaviour is gone for navigations: a route that suspends while it renders shows its nearest Suspense fallback instead of keeping the previous page on screen ([Suspense](https://react.dev/reference/react/Suspense#preventing-already-revealed-content-from-hiding)).

In every setting the address bar changes when the route's loaders have finished, before the new route renders, and a navigation started outside an action (a timer, a microtask, a handler) is still held in the first two settings: what holds it is the router's own `startTransition`, not where `navigate()` was called. The `flushSync` navigation option does not change this: for a route with loaders, it flushes only the "loading" state, not the new route.

Weigh the settings against each other:

- **For `true`:** a library action always runs inside a transition, so `fetcher.state` and `useNavigation()` read correctly while it is pending; left out, they stay at their old values until the action settles. The library's own pending and optimistic state do not depend on the setting: in the test app, an action that returned `navigate()` (next section) behaved the same with `true` and with the prop left out.
- **Against `true`:** React holds every transition until the pending async ones have settled ([Pending actions hold other transitions](action-props.md#pending-actions-hold-transitions)). With `true`, a slow `<Link>` or `<Form>` navigation is one of them for as long as its loaders run, so every part with an action prop or controlled state that the user opens meanwhile waits for it (an uncontrolled part with no action prop does not). In the test app, a tab clicked 40 ms into a 700 ms `<Link>` navigation switched its panel at 799 ms with `true`, when the navigation ended, and at 133 ms with the prop left out.
- **For `false`:** the only setting in which a pending save holds no navigation and no router hook. **Against:** route content that suspends shows a fallback, as above.

Use `true` when you read `fetcher.state` or `useNavigation()` inside components that library actions update and your navigations are fast. Leave it out when slow navigations would hold the UI. Use `false` when a navigation must not wait for a pending save (a command palette that navigates) and your routes do not suspend.

## Return the navigation from an action

In framework mode, the function from `useNavigate()` returns a promise that resolves when the navigation is complete ([useNavigate](https://reactrouter.com/api/hooks/useNavigate)). Return it from an action prop, and the control stays pending until the next page has rendered: the trigger shows the new value at once with `data-pending`, and the content changes in the same commit as the end of the pending state. This fits filters and sort orders kept in the URL.

Example: [Switch](../components/switch.md)

An "Unread only" filter. The loader reads `?unread=1`, and the Switch is controlled by the loader data. In the test app the Switch flipped at once, carried `data-pending` from 44 ms to 760 ms, and the filtered list appeared at 760 ms, with no intermediate state. A Combobox `valueChangeAction` that navigates to `?from=…` behaved the same (measured on React Router 7.18.7).

```tsx
import { useNavigate, useSearchParams } from "react-router";
import { Switch } from "@funstack/ui/switch";

function UnreadFilter({ unreadOnly }: { unreadOnly: boolean }) {
  const [params] = useSearchParams();
  const navigate = useNavigate();
  return (
    <label>
      <Switch
        checked={unreadOnly} // from loaderData
        checkedChangeAction={(next) => {
          const search = new URLSearchParams(params);
          if (next) search.set("unread", "1");
          else search.delete("unread");
          // Returned: pending until the filtered page has rendered.
          return navigate({ search: search.toString() }, { replace: true, preventScrollReset: true });
        }}
      />
      Unread only
    </label>
  );
}
```

`replace: true` keeps each toggle out of the history, and `preventScrollReset` keeps the scroll position. A navigation that the UI should not wait for is not returned ([Return the promise only when the UI must wait for it](action-props.md#await-only)).

## `Form.Root` with `useFetcher`

To post a `Form.Root` to a route action and keep the library's form behaviour, give it a function `action` that calls `fetcher.submit` and awaits it, and feed `fetcher.data` back as `errors` and `error` ([Field and Form: form-level errors](../components/field.md#form-level-errors)). In the test app, server field errors reached the right `Field.Error`, the first errored field was focused, `Form.Error` showed the form-level message, and `data-pending` was on the form, `Form.Submit` and the Fields for the whole submission.

```tsx
// app/routes/settings.tsx
import { data, useFetcher } from "react-router";
import { Field } from "@funstack/ui/field";
import { Form } from "@funstack/ui/form";
import type { FieldErrorValue, FormErrors } from "@funstack/ui/form";
import type { Route } from "./+types/settings";

type SettingsResult = { errors?: FormErrors; error?: FieldErrorValue; saved?: number };

export async function action({ request }: Route.ActionArgs) {
  const form = await request.formData();
  const displayName = String(form.get("displayName") ?? "").trim();
  // A rule only the server can check. A 4xx status skips the revalidation (see below).
  if (await db.isNameTaken(displayName)) {
    return data<SettingsResult>({ errors: { displayName: "That name is taken." } }, { status: 400 });
  }
  if (!(await db.available())) {
    return data<SettingsResult>({ error: "Could not save your settings. Try again." }, { status: 503 });
  }
  await db.saveSettings({ displayName });
  return data<SettingsResult>({ saved: Date.now() });
}

function GeneralForm({ displayName }: { displayName: string }) {
  const fetcher = useFetcher<typeof action>();
  return (
    <Form.Root
      autoReset={false} // a settings form keeps its values
      errors={fetcher.data?.errors}
      error={fetcher.data?.error}
      action={async (formData) => {
        await fetcher.submit(formData, { method: "post" }); // awaited: pending until it settles
      }}
    >
      <Form.Error />
      <Field.Root name="displayName" required>
        <Field.Label>Display name</Field.Label>
        <Field.Control defaultValue={displayName} />
        <Field.Error />
      </Field.Root>
      <Form.Submit>{({ pending }) => (pending ? "Saving…" : "Save")}</Form.Submit>
    </Form.Root>
  );
}
```

### The submission includes the revalidation

After a route action, React Router revalidates: in framework mode with SSR, [loaders are revalidated after every navigation and form submission](https://reactrouter.com/start/framework/route-module#shouldrevalidate). The promise of `fetcher.submit` resolves only when that revalidation has finished too. So the action above is pending for the route action plus every loader on the page, and while it is pending React holds every transition in the app ([Pending actions hold other transitions](action-props.md#pending-actions-hold-transitions)). In the test app the settings form was pending from 57 ms to 984 ms: the route action returned at 672 ms, and the revalidation took the rest. React holds every part with an action prop or controlled state opened in that time as long. How long such a hold is, measured in the same app on a Switch whose autosave took 700 ms: a tab clicked 40 ms into the save switched its panel at 727 ms, when the save ended.

To shorten the wait:

- Return a failure with a 4xx or 5xx status, as the action above does with `data(…, { status: 400 })`. After an action with a status of 400 or more, React Router does not revalidate by default ([Form Validation](https://reactrouter.com/how-to/form-validation)), so a rejected submission holds the UI for the action alone. In the test app a taken name sent no revalidation request, and the form was pending from 42 ms to 363 ms.
- Pass `defaultShouldRevalidate: false` to `fetcher.submit` when one submission changes nothing the page's loaders read (on React Router 7, stable from 7.15). It replaces the default for that call, including the 4xx rule above; a route's own `shouldRevalidate` receives it and still decides. In the test app a successful save with it sent no revalidation request and was pending from 44 ms to 660 ms.
- Export `shouldRevalidate` from the routes whose data the action does not change, so that their loaders are not called again.
- For a save that should not hold the UI (an autosave Switch, a menu item), post to a resource route with `fetch` and revalidate after the action has settled ([Refetch timing](#refetch)).

### Toasting the result

`Form.Root` never reads what its `action` returns, and `fetcher.submit` resolves with nothing: the result is `fetcher.data`, which a component reads in the render that commits it. Show a [toast](../components/toast.md) from an effect on `fetcher.data`, once the fetcher is idle: React Router sets `fetcher.data` when the route action returns, before the revalidation, and with `useTransitions` a component sees it then, while the form still shows its pending state. Each result is a new object, so comparing it with the last one shown gives one toast per result, even when the effect runs again for the same data:

```tsx
import { useEffect, useRef } from "react";
import { toast } from "@funstack/ui/toast";

function GeneralForm({ displayName }: { displayName: string }) {
  const fetcher = useFetcher<typeof action>();
  const data = fetcher.state === "idle" ? fetcher.data : undefined; // settled results only
  const shown = useRef<typeof data>(undefined);
  useEffect(() => {
    if (data === undefined || shown.current === data) return;
    shown.current = data;
    if (data.saved) toast({ title: "Settings saved", type: "success" });
    else if (data.error) {
      // FieldErrorValue: one message or several
      const description = [data.error].flat().filter(Boolean).join(" ");
      toast({ title: "Not saved", description, type: "error" });
    }
  }, [data]);
  // … the Form.Root above
}
```

A toast for field errors is usually not needed: the Form focuses the first errored field.

## <a id="refetch"></a>Refetch timing and optimistic lists

A control that saves through `fetch` to a resource route is not followed by a revalidation: start one yourself, after the action has settled. A refetch started inside the action would make every held transition wait for its data as well ([Start refetches after the action](action-props.md#refetch-after)). `useRevalidator().revalidate()` in a `setTimeout` does that.

A list that hides an item while its removal is saved then has a gap: the optimistic value ends when the action settles, but the loader data still has the item until the revalidation arrives, so the item would reappear for that time. Keep two layers over the loader data:

- a committed state, written when a save succeeds, that covers the gap until the new loader data arrives;
- a `useOptimistic` layer over it for the save in flight, which React drops when the action settles.

Example: [Menu](../components/menu.md)

Archive from a row's menu. While the save runs, the row is marked busy rather than removed: the open Menu whose item is running lives in that row, and removing the row would unmount it. Kept, the Menu stays open while the save runs, and on a failure `details.reject()` keeps it open on the same row, so the user can try again ([Handling a failed save](action-props.md#reject)).

```tsx
import { startTransition, useOptimistic, useState } from "react";
import { useRevalidator } from "react-router";
import { Menu } from "@funstack/ui/menu";
import { toast } from "@funstack/ui/toast";
import type { Rejectable } from "@funstack/ui/types";

type Patch = { readonly removed?: boolean; readonly busy?: boolean };
type Patches = Readonly<Record<string, Patch>>;

function applyPatch(patches: Patches, ids: readonly string[], patch: Patch): Patches {
  const next = { ...patches };
  for (const id of ids) next[id] = { ...next[id], ...patch };
  return next;
}

// Render it with key={folder}, so that a new folder starts with no patches.
function MessageList({ messages }: { messages: readonly Message[] }) {
  const revalidator = useRevalidator();
  const [committed, setCommitted] = useState<Patches>({});
  const [patches, addPatch] = useOptimistic(
    committed,
    (current: Patches, [ids, patch]: [readonly string[], Patch]) => applyPatch(current, ids, patch),
  );

  async function archive(ids: readonly string[], details: Rejectable) {
    addPatch([ids, { busy: true }]); // in flight: shown busy, still listed
    const response = await fetch("/api/messages", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ intent: "archive", ids }),
    });
    if (!response.ok) {
      toast({ title: "Not archived", type: "error" });
      details.reject(); // roll back, no Error Boundary
      return;
    }
    // After the await: wrapped, so it commits together with the end of the action.
    startTransition(() => setCommitted((current) => applyPatch(current, ids, { removed: true })));
    setTimeout(() => void revalidator.revalidate()); // after the action has settled
  }

  const rows = messages.filter((m) => !patches[m.id]?.removed);
  return (
    <ul>
      {rows.map((m) => (
        <li key={m.id} data-busy={patches[m.id]?.busy ? "" : undefined}>
          {m.subject}
          <Menu.Root>
            <Menu.Trigger aria-label={`Actions for ${m.subject}`}>⋯</Menu.Trigger>
            <Menu.Popup>
              <Menu.Item action={(details) => archive([m.id], details)}>
                {({ pending }) => (pending ? "Archiving…" : "Archive")}
              </Menu.Item>
            </Menu.Popup>
          </Menu.Root>
        </li>
      ))}
    </ul>
  );
}
```

When the revalidated data arrives without the item, its committed patch has nothing left to hide, so it can stay.

## Before hydration and without JavaScript

A function `action` on `Form.Root` is only progressive enhancement when it is a Server Function. A client function, such as the one that calls `fetcher.submit`, has no URL to post to: React renders it as `action="javascript:throw new Error('React form unexpectedly submitted.')"`, so the form cannot be submitted before hydration or without JavaScript.

A form that must work without JavaScript takes a string `action` and React Router's `fetcher.Form` as its element. Before hydration it is a plain HTML form: the browser posts it, the route action runs, and the page renders again with the result in `useActionData()`. After hydration the fetcher submits it, and the result is in `fetcher.data`. Pass whichever is set:

```tsx
import { useActionData, useFetcher } from "react-router";

function GeneralForm({ displayName }: { displayName: string }) {
  const fetcher = useFetcher<typeof action>();
  const postBack = useActionData<typeof action>(); // the result of a post made before hydration
  const result = fetcher.data ?? postBack;
  return (
    <Form.Root
      action="/settings"
      method="post"
      render={<fetcher.Form />}
      errors={result?.errors}
      error={result?.error}
    >
      {/* … the Fields; show your own pending state from fetcher.state */}
      <Form.Submit>{fetcher.state === "idle" ? "Save" : "Saving…"}</Form.Submit>
    </Form.Root>
  );
}
```

With a string `action`, `Form.Root` is a navigating form: it does not run the submission, and the fetcher's submit is not a React form action, so `useFormStatus` sees nothing. What you lose:

- `data-pending` and `state.pending` on the form, `Form.Submit` and the Fields. Read `fetcher.state` instead.
- Everything that happens when a submission settles: focusing the first errored field, announcing the form-level `error`, and `autoReset`.
- Showing errors again. `errors` are shown, and the user's edit hides a field's error, but only a settled submission shows that field's errors again, so a later error for an edited field stays hidden.

So choose per form: a function `action` with the full form behaviour after hydration, or a string `action` that also works without JavaScript.

Controls outside a form have the same limit: an action prop runs only after hydration. The components that work without JavaScript are the ones in [JS-free mode](browser-owned-state.md#js-free-mode) (for a navigation drawer that also closes on client navigation, see [Drawer](../components/drawer.md#navigation-drawer)).

## <a id="csp-nonce"></a>A CSP nonce from middleware

For a policy with a per-request nonce, create the nonce in React Router middleware and keep it in a router context. React Router 8 always runs middleware. React Router 7 runs it only with `future.v8_middleware: true` in `react-router.config.ts`. When you upgrade to 8, remove the flag: React Router 8 rejects it with a config error.

```tsx
// app/lib/nonce.server.ts
import { randomBytes } from "node:crypto";
import { createContext } from "react-router";
import type { MiddlewareFunction } from "react-router";

export const nonceContext = createContext<string>("");

export const nonceMiddleware: MiddlewareFunction<Response> = async ({ context }, next) => {
  context.set(nonceContext, randomBytes(16).toString("base64"));
  return next();
};
```

`entry.server.tsx` reads it from the load context, sends it in the header, and passes it to `<ServerRouter>` and to React for its scripts and hoisted styles. If the app has no `entry.server.tsx`, `npx react-router reveal entry.server` writes React Router's default entry into `app/`. Only the lines that change in it are shown:

```tsx
// app/entry.server.tsx
import type { EntryContext, RouterContextProvider } from "react-router";
import { nonceContext } from "./lib/nonce.server";

export default function handleRequest(
  request: Request,
  responseStatusCode: number,
  responseHeaders: Headers,
  routerContext: EntryContext,
  loadContext: RouterContextProvider,
) {
  const nonce = loadContext.get(nonceContext);
  responseHeaders.set(
    "Content-Security-Policy",
    `script-src 'self' 'nonce-${nonce}'; style-src 'self' 'nonce-${nonce}'`,
  );
  // … the default entry's HEAD response
  return new Promise((resolve, reject) => {
    // … the default entry's readyOption and timeout
    const { pipe, abort } = renderToPipeableStream(
      <ServerRouter context={routerContext} url={request.url} nonce={nonce} />,
      {
        // The same value for scripts and styles; CSPProvider gets it too.
        nonce: { script: nonce, style: nonce },
        // … [readyOption](), onShellError and onError, unchanged
      },
    );
  });
}
```

On React Router 7 the default entry types `loadContext` as `AppLoadContext`; with the middleware flag on, change it to `RouterContextProvider` as above. React Router 8's default entry already has it.

The root loader hands the same value to `CSPProvider` ([Content Security Policy](content-security-policy.md)). The policy above has no `style-src-attr 'unsafe-inline'`, so the provider also gets `inlineStyles="after-hydration"`: no library part renders a `style` attribute into the HTML ([No inline styles in the HTML](content-security-policy.md#inline-styles-after-hydration)).

The nonce must stay the document's for the page's whole life. The header that allows it came with the document, but the root loader runs again on every revalidation, and the middleware would give it a new nonce, which would reach `CSPProvider` while the page's policy still allows only the first. Opt the root route out of revalidation:

```tsx
// app/root.tsx
import { Links, Meta, Outlet, Scripts, ScrollRestoration, useRouteLoaderData } from "react-router";
import { CSPProvider } from "@funstack/ui/csp";
import type { Route } from "./+types/root";
import { nonceContext, nonceMiddleware } from "./lib/nonce.server";

export const middleware: Route.MiddlewareFunction[] = [nonceMiddleware];

export function loader({ context }: Route.LoaderArgs) {
  return { nonce: context.get(nonceContext) };
}

// The nonce belongs to the document's CSP header: never load a new one.
export function shouldRevalidate() {
  return false;
}

export function Layout({ children }: { children: React.ReactNode }) {
  const nonce = useRouteLoaderData<typeof loader>("root")?.nonce ?? "";
  return (
    <html lang="en">
      <head>
        {/* Vite's: the nonce for the styles and preloads Vite inserts, in development and in the build. */}
        <meta property="csp-nonce" nonce={nonce} />
        <Meta />
        <Links nonce={nonce} />
      </head>
      <body>
        <CSPProvider nonce={nonce} inlineStyles="after-hydration">
          {children}
        </CSPProvider>
        <ScrollRestoration nonce={nonce} />
        <Scripts nonce={nonce} />
      </body>
    </html>
  );
}

export default function App() {
  return <Outlet />;
}
```

In the test app, the revalidation after a settings save asked only for the settings route's data (`?_routes=routes/settings`), the page kept its first nonce, and the browser reported no CSP violation.

The `csp-nonce` meta is Vite's, not the library's, and it is needed in production too. [Vite uses its nonce](https://vite.dev/guide/features#content-security-policy-csp) "during both dev and after build": for the `<style>` elements its development server injects, and for the `<link>` elements a production build inserts to preload the CSS and modules of a dynamic `import()`.
