# React Router (https://0758e0c7.effetch-query.pages.dev/docs/frameworks/react-router)

React Router's framework mode needs no integration package: the core and
`./react` cover it. A root
middleware gives each request its own client, which loaders read from the
router's context, and `QueryClient.disposeAfter` disposes it once the
response is sent.

The examples import `api.ts`, `client.ts` and `todos.ts` from [Getting started](https://0758e0c7.effetch-query.pages.dev/docs/getting-started), and `todo-list.tsx` from [Send the cache](https://0758e0c7.effetch-query.pages.dev/docs/server-rendering).

**1. Make a client per request in a middleware.** It puts the client in
the router's context, and wraps the response so the client lives until
the streamed body is sent:

```ts query-context.ts
import * as ManagedRuntime from "effect/ManagedRuntime";

import { QueryClient } from "@monarcode/effetch-query";
import {
  createContext,
  data,
  type MiddlewareFunction,
  type RouterContextProvider,
} from "react-router";

import { ApiClientLive } from "./api.js";

// Builds your services once per process, for every request's client.
const appRuntime = ManagedRuntime.make(ApiClientLive);

// `null` where the middleware didn't run: React Router runs none for a URL
// no route matches.
export const queryClientContext = createContext<QueryClient.QueryClient | null>(
  null,
);

/** The request's client, in a loader or action. */
export const getQueryClient = (
  context: Readonly<RouterContextProvider>,
): QueryClient.QueryClient => {
  const client = context.get(queryClientContext);
  if (client === null) {
    throw data("app/root.tsx doesn't export queryClientMiddleware", {
      status: 500,
    });
  }
  return client;
};

// React Router resumes middleware once the page's shell is ready, while the
// body still streams, so the client is disposed once the body is sent.
export const queryClientMiddleware: MiddlewareFunction<Response> = async (
  { context },
  next,
) => {
  const client = QueryClient.make({ runtime: appRuntime });
  context.set(queryClientContext, client);
  return QueryClient.disposeAfter(client, await next());
};
```

**2. Run it for every request.** `app/root.tsx` exports it, so it runs for
every request that runs a loader:

```ts
import { queryClientMiddleware } from "./query-context.js";

export const middleware = [queryClientMiddleware];
```

**3. Prefetch in loaders.** A route's loader prefetches into the request's
client and returns its state, which the route hands to a
`HydrationBoundary`:

```tsx
import { QueryClient } from "@monarcode/effetch-query";
import { HydrationBoundary } from "@monarcode/effetch-query/react";
import { type LoaderFunctionArgs, useLoaderData } from "react-router";

import { getQueryClient } from "./query-context.js";
import { TodoList } from "./todo-list.js";
import { todos } from "./todos.js";

export async function loader({ context }: LoaderFunctionArgs) {
  const client = getQueryClient(context);
  await client.prefetch(todos());
  return { state: QueryClient.dehydrate(client, { pending: "promise" }) };
}

export default function TodosRoute() {
  const { state } = useLoaderData<typeof loader>();
  return (
    <HydrationBoundary state={state}>
      <TodoList />
    </HydrationBoundary>
  );
}
```

With React Router's generated route types (`react-router typegen`), type
the loader with `Route.LoaderArgs` and read the state from the component's
`loaderData` prop (`Route.ComponentProps`), as the
[`react-router` example](https://github.com/monarcode/effetch-query/tree/main/examples/react-router) does.

**4. Give the server render the request's client.** To get the entry
files, run `npx react-router reveal`. In `entry.server.tsx`,
`handleRequest` gets the router's context as `loadContext`; render the
following where it renders `<ServerRouter>`:

```tsx
import { QueryProvider } from "@monarcode/effetch-query/react";
import {
  type EntryContext,
  type RouterContextProvider,
  ServerRouter,
} from "react-router";

import { queryClientContext } from "./query-context.js";

export function ServerApp(props: {
  readonly request: Request;
  readonly routerContext: EntryContext;
  readonly loadContext: RouterContextProvider;
}) {
  const client = props.loadContext.get(queryClientContext);
  const router = (
    <ServerRouter context={props.routerContext} url={props.request.url} />
  );
  return client === null ? (
    router
  ) : (
    <QueryProvider client={client}>{router}</QueryProvider>
  );
}
```

**5. Give the browser one client.** In `entry.client.tsx`, the browser gets
one client for the page's lifetime:

```tsx
import { QueryProvider } from "@monarcode/effetch-query/react";
import { StrictMode, startTransition } from "react";
import { hydrateRoot } from "react-dom/client";
import { HydratedRouter } from "react-router/dom";

import { queryClient } from "./client.js";

startTransition(() => {
  hydrateRoot(
    document,
    <StrictMode>
      <QueryProvider client={queryClient}>
        <HydratedRouter />
      </QueryProvider>
    </StrictMode>,
  );
});
```

A few things to know about React Router:

- **A query still loading streams in:** React Router streams the promises
  in loader data. Start a prefetch without awaiting it,
  `void client.prefetch(query)`, and the page renders at once. One still
  loading at the entry's `streamTimeout` is fetched in the browser instead.
- **On navigation**, the loaders run through a `.data` request, which
  brings the page's state the same way. Each navigation runs them again,
  with a new client, so they refetch on the server whatever the browser
  has cached; where that's too much, export `shouldRevalidate` from the
  route, or a `clientLoader` that prefetches into the browser's client.
- **Redirect from loaders.** A query whose run dies with `redirect()`, made
  inside the Effect
  (`Effect.suspend(() => Effect.die(redirect("/login")))`), makes
  `client.fetch` reject with the `Response`, and the router follows it.
  Load such a query with `client.fetch` in the loader.
- **Guard a layout in middleware.** To check the user once for every page
  under a layout, fetch the query in the layout route's `middleware` and
  `clientMiddleware`, which run before its pages' loaders, and put the
  value in a router context (`createContext`) for those loaders to read.
  The [`react-router` example](https://github.com/monarcode/effetch-query/tree/main/examples/react-router) does this with
  the signed-in user. The pages' loaders wait for it, so give the query a
  `staleTime`: while it's fresh, `fetch` answers from the cache at once.