Skip to Content
Effetch Query
Frameworks

React Router

Use Effetch Query in React Router's framework mode.

Your app uses React Router's framework mode, with server rendering. A root middleware gives each request its own client, which loaders read from the router's context, and QueryClient.disposeAfter disposes it after the response is sent. In the browser, one client serves the page's components and its client loaders. React Router needs no integration package: the core and ./react cover it.

This page shows React Router's wiring. The rules every framework shares, a staleTime, streaming and redirects, are in Frameworks, and the round trip itself is in Send the cache. The examples import api.ts, client.ts and todos.ts from Getting started, and todo-list.tsx from Send the cache. client.ts makes the browser's client, with a 30-second staleTime.

Before you begin

You need:

  • React 19;
  • React Router 8, in framework mode with server rendering. Effetch Query is built and tested against React Router 8.5.2;
  • the entry files, entry.server.tsx and entry.client.tsx. To get them, run npx react-router reveal.

1. Make a client per request in a middleware

The middleware 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. In the browser, `entry.client.tsx` sets the page's client.
export const  = <. | null>(
  null,
);

/** The request's client in a loader, or the page's in a client loader. */
export const  = (
  : <>,
): . => {
  const  = .();
  if ( === null) {
    throw ("No query client: see app/root.tsx and entry.client.tsx", {
      : 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 the middleware for every request

Export it from app/root.tsx, 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

In entry.server.tsx, wrap the router in a QueryProvider for the request's client:

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 ? (
    
  ) : (
    < ={}>{}</>
  );
}

handleRequest gets the router's context as its fifth argument, loadContext. Render ServerApp where it renders <ServerRouter>, passing it request, routerContext and loadContext. The example's entry.server.tsx does the same inline.

5. Give the browser one client

In entry.client.tsx, the browser gets one client for the page's lifetime. Give it to the QueryProvider, for components, and to the router's context with getContext, for client middleware and client loaders:

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

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

// `getQueryClient(context)` returns the page's client in the browser.
const  = () =>
  new (new ([[, ]]));

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

Without getContext, the router's context in the browser holds no client, and getQueryClient throws its 500 on the first client navigation that runs a client loader or client middleware.

Stream a query

React Router streams the promises in loader data. Start a prefetch without awaiting it, and the page renders at once:

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

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

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

A query still loading at the server entry's streamTimeout is fetched in the browser instead.

Load in the browser on navigation

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 loads into the browser's client:

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

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

// The first page load: the server fetches, and sends what it loaded.
export async function ({  }: ) {
  const  = ();
  await .(());
  return { : .() };
}

// Later navigations: the page's client fetches only what's stale.
export async function ({  }: ) {
  await ().(());
  return { :  };
}

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

A clientLoader needs step 5's getContext, so that getQueryClient finds the page's client.

Redirect from a loader

A query whose run dies with redirect() makes client.fetch reject with the Response, and the router follows it. Make the redirect inside the Effect, with Effect.die, as Redirect from a query explains:

current-user.ts
import * as  from "effect/Effect";
import * as  from "effect/Schema";

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

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

export const  = .({ : . });

export const  = .({
  : ["current-user"],
  : .(() => .("/me", { :  })).(
    .("HttpError", () =>
      . === 401
        ? .(("/login"))
        : .(),
    ),
  ),
  : { :  },
});

Load it with client.fetch in the loader, as await getQueryClient(context).fetch(currentUser).

Guard a layout

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. Put the user in a router context for those loaders to read:

import {
  ,
  type ,
  type ,
} from "react-router";

import { , type  } from "./current-user.js";
import {  } from "./query-context.js";

export const  = <typeof .>();

// Runs on the server and in the browser. Signed out, the query dies with a
// redirect to /login, and the router follows it.
const  = async ({
  ,
}: {
  readonly : <>;
}) => {
  .(, await ().());
};

export const  = [];
export const  = [];

// In a page under the layout:
export function ({  }: ) {
  return { : .(). };
}

clientMiddleware reads the page's client, so it needs step 5's getContext too. The react-router example does this with the signed-in user. The pages' loaders wait for the guard, so give its query a staleTime: while it's fresh, fetch answers from the cache at once.

What's next

On this page