# Send the cache (https://effetch-query.monarcode.dev/docs/server-rendering)

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](https://effetch-query.monarcode.dev/docs/frameworks).

The examples import `api.ts`, `client.ts` and `todos.ts` from
[Getting started](https://effetch-query.monarcode.dev/docs/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](https://effetch-query.monarcode.dev/docs/queries/freshness).
- **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](https://effetch-query.monarcode.dev/docs/queries/without-effetch) shows.

A failed query stays on the server unless you ask to send it.
[What's sent](https://effetch-query.monarcode.dev/docs/server-rendering/whats-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:

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

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

export function TodoList() {
  const { value } = useSuspenseQuery(todos());
  return (
    <ul>
      {value.map((todo) => (
        <li key={todo.id}>{todo.title}</li>
      ))}
    </ul>
  );
}
```

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

```tsx
import * as ManagedRuntime from "effect/ManagedRuntime";

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

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

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

export async function renderPage(): Promise<string> {
  // One client per request, so one user's data never reaches another's page.
  const client = QueryClient.make({ runtime: appRuntime });
  try {
    await client.prefetch(todos());
    const state = QueryClient.dehydrate(client);
    const html = renderToString(
      <QueryProvider client={client}>
        <HydrationBoundary state={state}>
          <TodoList />
        </HydrationBoundary>
      </QueryProvider>,
    );
    // `<` is escaped so a value can't close the script tag.
    const json = JSON.stringify(state).replace(/</g, "\\u003c");
    return `<div id="root">${html}</div>
<script id="query-state" type="application/json">${json}</script>`;
  } finally {
    await client.dispose();
  }
}
```

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](https://effetch-query.monarcode.dev/docs/client#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:

```tsx
import { QueryClient } from "@monarcode/effetch-query";
import {
  HydrationBoundary,
  QueryProvider,
} from "@monarcode/effetch-query/react";
import { hydrateRoot } from "react-dom/client";

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

const state = JSON.parse(
  document.getElementById("query-state")?.textContent ?? "[]",
) as QueryClient.DehydratedState;

const root = document.getElementById("root");
if (root !== null) {
  hydrateRoot(
    root,
    <QueryProvider client={queryClient}>
      <HydrationBoundary state={state}>
        <TodoList />
      </HydrationBoundary>
    </QueryProvider>,
  );
}
```

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](https://effetch-query.monarcode.dev/docs/server-rendering/streaming)
  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](https://effetch-query.monarcode.dev/docs/cache/accounts) explains.

## Load the cache without React

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

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

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

const state = JSON.parse(
  document.getElementById("query-state")?.textContent ?? "[]",
) as QueryClient.DehydratedState;

QueryClient.hydrate(queryClient, state);
```

`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

- [What's sent](https://effetch-query.monarcode.dev/docs/server-rendering/whats-sent): which queries cross,
  schemas that transform, keys, and sending failures.
- [Stream the cache](https://effetch-query.monarcode.dev/docs/server-rendering/streaming): send the page
  before every query has loaded.
- [Frameworks](https://effetch-query.monarcode.dev/docs/frameworks): the same round trip in TanStack Start,
  Next.js and React Router.
- [Sign out and switch accounts](https://effetch-query.monarcode.dev/docs/cache/accounts): keep one user's
  server state away from the next.