Skip to Content
Effetch Query
Server rendering

Send the cache

Fill the cache on the server, send it with the page, and load it in the browser.

Your app renders on the server, and you want each page to arrive with its data in the HTML rather than a loading state. The server loads what the page needs into a query client, renders the page, and sends the client's cache with it. The browser loads that cache into its own client before it renders, so its first render matches the server's HTML, and nothing is fetched again while the values are fresh.

Two words name the round trip, as in TanStack Query. To dehydrate is to read a client's cache as JSON, to send with the page. To hydrate is to load that JSON into the browser's client. This page shows the three steps with any React server renderer (renderToString, renderToPipeableStream, a framework's), and how to hydrate without React. If you use a framework, read this page first, then Frameworks.

The examples import api.ts, client.ts and todos.ts from Getting started.

Before you begin

Two things decide whether a value reaches the browser and stays there:

  • Give your queries a staleTime. The default is zero, so a value is already stale when it reaches the browser. useQuery refetches it as it mounts, and useSuspenseQuery does when it mounts more than a second after the server fetched it. Getting started's client.ts sets 30 seconds for every query. See Freshness and refetching.
  • A query needs a schema to be sent. Values travel as JSON, so a query needs a schema to encode its value on the server and decode it in the browser. An Effetch endpoint's output is its schema, so endpoint queries need nothing more. A query of your own needs a schema, as Queries from any Effect shows.

A failed query stays on the server unless you ask to send it. What's sent has the rules for schemas, keys and failures.

1. Read the query with Suspense

Here's a component that reads the todos with useSuspenseQuery. When the cache already holds them, as it will on the server, it renders the list straight away:

todo-list.tsx
import {  } from "@monarcode/effetch-query/react";

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

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

2. Load the data on the server

Make a client for the request, load what the page needs, and send QueryClient.dehydrate's result with the HTML:

import * as  from "effect/ManagedRuntime";

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

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

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

export async function (): Promise<string> {
  // One client per request, so one user's data never reaches another's page.
  const  = .({ :  });
  try {
    await .(());
    const  = .();
    const  = (
      < ={}>
        < ={}>
          < />
        </>
      </>,
    );
    // `<` is escaped so a value can't close the script tag.
    const  = .().(/</g, "\\u003c");
    return `<div id="root">${}</div>
<script id="query-state" type="application/json">${}</script>`;
  } finally {
    await .();
  }
}

Here's what each part does:

  • A client per request. One server process serves many requests, and each gets its own client, so one user's data never reaches another's page. It's cheap: with a runtime, every request's client shares your services, as Share your runtime explains. dispose() releases the client when the request is done.
  • client.prefetch loads the todos into the client before the render.
  • QueryClient.dehydrate reads the cache without fetching. Each value carries the time it was fetched, so a query is as fresh in the browser as it was on the server, as long as the two clocks agree. A stale query is sent stale, and refetches in the browser.

3. Load the cache in the browser

In the browser, render the same tree under a HydrationBoundary, and give it what the server sent:

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

import {  } from "./client.js";
import {  } from "./todo-list.js";

const  = .(
  .("query-state")?. ?? "[]",
) as .;

const  = .("root");
if ( !== null) {
  (
    ,
    < ={}>
      < ={}>
        < />
      </>
    </>,
  );
}

The first render shows the server's values, so it matches the server's HTML, and nothing is fetched until they're stale. The browser keeps one client, queryClient from client.ts, for the page's lifetime.

How a boundary loads

A boundary can sit anywhere, such as one per route, given each page's state as you navigate. It loads into the client of the nearest QueryProvider, and throws a MissingQueryProviderError without one. How it loads depends on what's cached:

  • A query that isn't cached loads during render, so the children read it in the same pass.
  • A query already cached takes the new value only if it's newer. It loads after commit, so a transition that brings new state doesn't change the page it leaves until React shows the new one.
  • A query the server was still loading waits for its result instead of fetching, as Stream the cache explains.
  • A value its schema can't decode is dropped, and the query fetches.

Under a QueryProvider whose resetKey changes, a boundary loads only what the server dehydrated after the change, as Sign out and switch accounts explains.

Load the cache without React

Call QueryClient.hydrate(client, state) before reading the queries:

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

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

const  = .(
  .("query-state")?. ?? "[]",
) as .;

.(, );

hydrate loads each query by a boundary's rules for what's cached, except that everything loads at once, and no resetKey filters it. It also loads state from Effect's own Hydration.dehydrate, for other atoms.

What's next

On this page