Skip to Content
Effetch Query
Frameworks

React Router

Use Effetch Query in React Router's framework mode.

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, and todo-list.tsx from Send the cache.

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:

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

import {  } from "@monarcode/effetch-query";
import {
  ,
  ,
  type ,
  type ,
} from "react-router";

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

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

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

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

// 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 : <Response> = async (
  {  },
  ,
) => {
  const  = .({ :  });
  .(, );
  return .(, await ());
};

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

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

export const  = [];

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:

import {  } from "@monarcode/effetch-query";
import {  } from "@monarcode/effetch-query/react";
import { type ,  } from "react-router";

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

export async function ({  }: ) {
  const  = ();
  await .(());
  return { : .(, { : "promise" }) };
}

export default function () {
  const {  } = <typeof >();
  return (
    < ={}>
      < />
    </>
  );
}

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 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>:

import {  } from "@monarcode/effetch-query/react";
import {
  type EntryContext,
  type ,
  ,
} from "react-router";

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

export function (: {
  readonly : Request;
  readonly : EntryContext;
  readonly : ;
}) {
  const  = ..();
  const  = (
    < ={.} ={..} />
  );
  return  === null ? (
    
  ) : (
    < ={}>{}</>
  );
}

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

import {  } from "@monarcode/effetch-query/react";
import { ,  } from "react";
import {  } from "react-dom/client";
import {  } from "react-router/dom";

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

(() => {
  (
    ,
    <>
      < ={}>
        < />
      </>
    </>,
  );
});

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 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.