# QueryClient (https://effetch-query.monarcode.dev/docs/reference/query-client)

`QueryClient` makes the client that holds the cache and runs your queries, and sends that cache from a server. Import it from the core entry point:

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

Its exports follow, grouped by the guide that covers them, each with its
docs. Your editor shows the same docs, with an example, when you hover the
name.

## The client

Guide: [The query client](https://effetch-query.monarcode.dev/docs/client).

### QueryClient.make

Creates a [`QueryClient`](https://effetch-query.monarcode.dev/docs/reference/query-client#queryclient). Nothing is built until the client is first used: then it builds `layer` once and keeps it until `QueryClient.dispose`. Given a `runtime` instead, it uses the runtime's services and builds none of its own ([`RuntimeOptions`](https://effetch-query.monarcode.dev/docs/reference/query-client#runtimeoptions)). With no services declared in [`Register`](https://effetch-query.monarcode.dev/docs/reference/query-client#register), the options can be left out ([`OptionalOptions`](https://effetch-query.monarcode.dev/docs/reference/query-client#optionaloptions)).

### QueryClient.QueryClient

A query cache with its own `AtomRegistry.AtomRegistry`, and your services from its own build of your layer or from your runtime. Create one with [`make`](https://effetch-query.monarcode.dev/docs/reference/query-client#make) (or [`layer`](https://effetch-query.monarcode.dev/docs/reference/query-client#layer) in Effect programs). Every query, mutation and Effect-side cache function runs with it, as the [`QueryClient`](https://effetch-query.monarcode.dev/docs/reference/query-client#queryclient) service.

A client is cheap to create. On a server, create one per request from your process's runtime ([`RuntimeOptions`](https://effetch-query.monarcode.dev/docs/reference/query-client#runtimeoptions)) and `QueryClient.dispose` it when the response is done.

The service every Effect-side cache function needs. Queries, mutations and the client's hooks already run with it; elsewhere, run the Effect with `QueryClient.runPromise` or provide [`layer`](https://effetch-query.monarcode.dev/docs/reference/query-client#layer).

| Prop             | Type       | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| ---------------- | ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `registry`       | `object`   | The registry that holds this client's cache, for `@effect/atom-react` and your own atoms. Don't `reset` or `dispose` it: use QueryClient.dispose. Its `onNodeAdded` and `onNodeRemoved` hooks are the client's: replacing them breaks invalidation.                                                                                                                                                                                                                                                                                                                                                                                                                   |
| `runPromise`     | `function` | Runs an Effect with your services and this client, for code outside Effect such as a router loader. `Reactivity` is provided too, the instance the cache listens to, so `Reactivity.invalidate` run here refetches queries that declare those keys. If the Effect fails, rejects with its error (`Cause.squash`), as `Effect.runPromise` does. Pass `{ signal }` to interrupt it when the signal aborts.                                                                                                                                                                                                                                                              |
| `runPromiseExit` | `function` | Like QueryClient.runPromise, but resolves with the `Exit` instead of rejecting.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       |
| `fetch`          | `function` | Returns a query's value, as Query.fetch does: the cached one if it's fresh, otherwise the result of a new fetch, joining one in progress. Rejects as QueryClient.runPromise does if the query fails, so a router's `redirect()` thrown by a query still reaches the router. Pass `{ signal }` to stop waiting when the signal aborts.                                                                                                                                                                                                                                                                                                                                 |
| `prefetch`       | `function` | Fetches a query unless its value is fresh, as Query.prefetch does, and resolves when the fetch settles. Never rejects: a failure shows in the query's result. Call it without `await` to start a fetch a component reads later, such as in a router loader that streams.                                                                                                                                                                                                                                                                                                                                                                                              |
| `invalidate`     | `function` | Marks the target's queries stale, as Query.invalidate does: those in use refetch at once, the rest the next time they're used. Without a target, every query. Resolves at once, without waiting for the refetches, and does nothing on a disposed client. Rejects with a Query.KeyHoldsTargetError for a key that holds queries (Query.Target).                                                                                                                                                                                                                                                                                                                       |
| `refetch`        | `function` | Refetches the target's queries that are in use, as Query.refetch does, and resolves when they've all settled. Without a target, every query in use. A query that fails doesn't reject it: each shows its own failure. It rejects only with a defect, such as a Query.KeyHoldsTargetError for a key that holds queries (Query.Target). On a disposed client, it resolves at once.                                                                                                                                                                                                                                                                                      |
| `reset`          | `function` | Puts the target's queries back to `Initial`, as Query.reset does, dropping their values: those in use fetch again at once, the rest the next time they're used. Without a target, every query. Resolves at once, without waiting for the fetches, and does nothing on a disposed client. Rejects as QueryClient.invalidate does.                                                                                                                                                                                                                                                                                                                                      |
| `clear`          | `function` | Drops the target's values without fetching, as Query.clear does, and those of the queries that read them: queries in use show `Initial` until something asks for them, such as a component that starts using one. Without a target, every query: use it on signing out, when refetching would fail. Resolves at once, and does nothing on a disposed client. Rejects as QueryClient.invalidate does.                                                                                                                                                                                                                                                                  |
| `dispose`        | `function` | Releases everything the client owns. It disposes the cache and clears its timers, then interrupts what's in progress: fetches, mutation runs, and the Effects started by QueryClient.runPromise. Last, it closes the layer's scope. An interrupted mutation run doesn't roll back its optimistic writes, since the cache is already gone. A layer build in progress is waited for, not cut short, because a memo map shared with your app runtime would keep the interruption. Resolves once everything interrupted and the layer's finalizers have run. If a finalizer throws, the layer is still released and the promise rejects. Don't use the client afterwards. |

### QueryClient.layer

Creates a [`QueryClient`](https://effetch-query.monarcode.dev/docs/reference/query-client#queryclient) as a layer, for Effect programs and tests without React. The client is disposed when the layer's scope closes.

Unless `options.memoMap` is set, the client builds `options.layer` with the memo map of the layer graph it's built in, so services that graph also builds are built once. A client given `options.runtime` uses the runtime's services instead. With no services declared in [`Register`](https://effetch-query.monarcode.dev/docs/reference/query-client#register), the options can be left out ([`OptionalOptions`](https://effetch-query.monarcode.dev/docs/reference/query-client#optionaloptions)).

### QueryClient.CommonOptions

The [`Options`](https://effetch-query.monarcode.dev/docs/reference/query-client#options) every client takes, whether it's given a layer or a runtime.

| Prop         | Type     | Description                                                      |
| ------------ | -------- | ---------------------------------------------------------------- |
| `signals?`   | `object` | The source of focus and reconnect. Default: `Signals.browser`.   |
| `queries?`   | `object` | Defaults and app-wide hooks for every query.                     |
| `mutations?` | `object` | Defaults and app-wide hooks for every mutation.                  |
| `entities?`  | `object` | Entities whose cached copies are kept in sync (EntitiesOptions). |

### QueryClient.LayerOptions

[`Options`](https://effetch-query.monarcode.dev/docs/reference/query-client#options) that give the client a layer, which it builds itself.

| Prop         | Type     | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| ------------ | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `layer`      | `object` | Provides the services declared in Register. The client builds it the first time it's needed and keeps it until QueryClient.dispose. If it fails to build, everything that needs it dies with that failure.                                                                                                                                                                                                                                                                                                                                |
| `memoMap?`   | `object` | The memo map to build `layer` with, so layers built with it before are shared rather than built twice: pass a `ManagedRuntime`'s `memoMap` when the client adds services of its own to the runtime's (with none, pass the runtime itself, RuntimeOptions). Default: a new one, or for layer the memo map of the layer graph the client is built in. Clients that share a memo map also share one `Reactivity`, so a `Reactivity.invalidate` in one refetches the matching queries of all of them. No cached values cross between clients. |
| `runtime?`   | `undefined` | Not with a layer: see RuntimeOptions.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `signals?`   | `object` | The source of focus and reconnect. Default: `Signals.browser`.                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| `queries?`   | `object` | Defaults and app-wide hooks for every query.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| `mutations?` | `object` | Defaults and app-wide hooks for every mutation.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| `entities?`  | `object` | Entities whose cached copies are kept in sync (EntitiesOptions).                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |

### QueryClient.OptionalOptions

The parameters of [`make`](https://effetch-query.monarcode.dev/docs/reference/query-client#make) and [`layer`](https://effetch-query.monarcode.dev/docs/reference/query-client#layer). With no services declared in [`Register`](https://effetch-query.monarcode.dev/docs/reference/query-client#register), the options can be left out, or given without a layer or a runtime. With services declared, it's `[options: Options]`, so a client must be given them.

### QueryClient.Options

Options for [`make`](https://effetch-query.monarcode.dev/docs/reference/query-client#make) and [`layer`](https://effetch-query.monarcode.dev/docs/reference/query-client#layer): your services, as a layer ([`LayerOptions`](https://effetch-query.monarcode.dev/docs/reference/query-client#layeroptions)) or a runtime that already provides them ([`RuntimeOptions`](https://effetch-query.monarcode.dev/docs/reference/query-client#runtimeoptions)), with the [`CommonOptions`](https://effetch-query.monarcode.dev/docs/reference/query-client#commonoptions).

### QueryClient.Register

Declares the services your queries and mutations run with. Augment it once, next to your composition root, and every definition, client hook and `QueryClient.runPromise` is typed against it:

- [`make`](https://effetch-query.monarcode.dev/docs/reference/query-client#make) requires a layer or a runtime that provides these services.
- An Effect that needs a service outside them doesn't compile.

Without the augmentation, [`Services`](https://effetch-query.monarcode.dev/docs/reference/query-client#services) is `never`, so anything that needs a service fails to compile.

### QueryClient.Requirements

What queries, mutations and the client's hooks run with: your [`Services`](https://effetch-query.monarcode.dev/docs/reference/query-client#services) and the [`QueryClient`](https://effetch-query.monarcode.dev/docs/reference/query-client#queryclient).

### QueryClient.RuntimeOptions

[`Options`](https://effetch-query.monarcode.dev/docs/reference/query-client#options) that give the client a `ManagedRuntime` providing your services, built once for every client that uses it. Share one runtime per process: on a server, each request's client then reuses its services rather than building them again.

The client doesn't own the runtime: `QueryClient.dispose` leaves it running. The runtime builds its layer the first time any client needs it; if that fails, or the runtime has been disposed, everything that needs it dies.

The client builds its own parts with the runtime's `memoMap`, so it shares the runtime's `Reactivity` with the services the runtime built (an SQL client publishes on it) and with the runtime's other clients: a `Reactivity.invalidate` in any of them refetches the matching queries of all. No cached values cross between clients.

| Prop         | Type     | Description                                                      |
| ------------ | -------- | ---------------------------------------------------------------- |
| `runtime`    | `object` | Provides the services declared in Register.                      |
| `layer?`     | `undefined` | Not with a runtime, which provides the services.                 |
| `memoMap?`   | `undefined` | Not with a runtime: the client uses the runtime's.               |
| `signals?`   | `object` | The source of focus and reconnect. Default: `Signals.browser`.   |
| `queries?`   | `object` | Defaults and app-wide hooks for every query.                     |
| `mutations?` | `object` | Defaults and app-wide hooks for every mutation.                  |
| `entities?`  | `object` | Entities whose cached copies are kept in sync (EntitiesOptions). |

### QueryClient.Services

The services declared in [`Register`](https://effetch-query.monarcode.dev/docs/reference/query-client#register), or `never` without the augmentation.

## Defaults and app-wide hooks

Guide: [Defaults and app-wide hooks](https://effetch-query.monarcode.dev/docs/client/defaults).

### QueryClient.Hook

An app-wide hook in [`QueriesOptions`](https://effetch-query.monarcode.dev/docs/reference/query-client#queriesoptions) or [`MutationsOptions`](https://effetch-query.monarcode.dev/docs/reference/query-client#mutationsoptions): it receives an event and runs with your services and the client. It can't fail; handle errors inside it. A hook that dies is logged, and the others still run. Query hooks run in a fiber of their own, after the query shows its result, so a slow hook doesn't hold the query up. Mutation hooks are part of the run: it completes after them.

### QueryClient.MutationDefaults

Options every mutation takes, set for all of them in `MutationsOptions.defaults`. A mutation's own options (`Mutation.MakeOptions`) extend these, with `E` its error type.

| Prop          | Type     | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| ------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `retry?`      | `object` | Retries a failed run on this schedule, which gets each failure. Defects aren't retried. Default: no retries.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| `concurrent?` | `union`  | The policy for how one use's runs (one component's `useMutation`, say) overlap. Separate uses, and `Mutation.run` calls, never affect each other. Default: `true`. - `true`: runs overlap. - `false`: a new run interrupts the one in progress, whose optimistic writes are rolled back first. - `"queue"`: a new run waits until the ones before it have settled, so runs go one at a time, in order. A queued run counts as in progress (`useIsMutating`, `useMutationState`), but its `optimistic` runs when it starts, so a run that fails rolls back only its own writes. - `"drop"`: a new run is ignored while the one the use shows is in progress, such as a second click on a submit button. It never starts or calls anything, and its `run` resolves at once with an interrupted `Exit`. After `reset`, which stops showing a run, a new run starts. |

### QueryClient.MutationFailed

What `MutationsOptions.onFailure` receives.

| Prop        | Type      | Description                                       |
| ----------- | --------- | ------------------------------------------------- |
| `mutation`  | `object`  | The mutation's definition, to compare with yours. |
| `variables` | `unknown` | What the mutation was called with.                |
| `cause`     | `object`  | Why the run failed, after `retry`.                |

### QueryClient.MutationSettled

What `MutationsOptions.onSettled` receives.

| Prop        | Type                     | Description                                       |
| ----------- | ------------------------ | ------------------------------------------------- |
| `mutation`  | `object`                 | The mutation's definition, to compare with yours. |
| `variables` | `unknown`                | What the mutation was called with.                |
| `exit`      | `Exit<unknown, unknown>` | How the run ended, after `retry`.                 |

### QueryClient.MutationsOptions

The `mutations` group of [`Options`](https://effetch-query.monarcode.dev/docs/reference/query-client#options): defaults for every mutation, and hooks that run on every run, after the mutation's own callbacks. The hooks run with your services. Interruptions never reach them.

| Prop         | Type           | Description                                                                                                    |
| ------------ | -------------- | -------------------------------------------------------------------------------------------------------------- |
| `defaults?`  | `object`       | Options for every mutation. A mutation's own options override them.                                            |
| `onMutate?`  | `Hook<object>` | Runs before each run's `run`, after its optimistic writes.                                                     |
| `onSuccess?` | `Hook<object>` | Runs after each successful run, after its `onSuccess` and `invalidates`.                                       |
| `onFailure?` | `Hook<object>` | Runs after each failed run, after its optimistic writes are rolled back and its `onFailure` ran.               |
| `onSettled?` | `Hook<object>` | Runs after each run that succeeds or fails, after its `onSettled`. None of the hooks run past an interruption. |

### QueryClient.MutationStarted

What `MutationsOptions.onMutate` receives.

| Prop        | Type      | Description                                       |
| ----------- | --------- | ------------------------------------------------- |
| `mutation`  | `object`  | The mutation's definition, to compare with yours. |
| `variables` | `unknown` | What the mutation was called with.                |

### QueryClient.MutationSucceeded

What `MutationsOptions.onSuccess` receives.

| Prop        | Type      | Description                                       |
| ----------- | --------- | ------------------------------------------------- |
| `mutation`  | `object`  | The mutation's definition, to compare with yours. |
| `variables` | `unknown` | What the mutation was called with.                |
| `value`     | `unknown` | What the run returned.                            |

### QueryClient.QueriesOptions

The `queries` group of [`Options`](https://effetch-query.monarcode.dev/docs/reference/query-client#options): defaults for every query, and hooks that run on every fetch. The hooks run with your services, after the query's `retry`. Interruptions never reach them.

| Prop         | Type           | Description                                                                                                                                                                                 |
| ------------ | -------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `defaults?`  | `object`       | Options for every query. A query's own options override them.                                                                                                                               |
| `onSuccess?` | `Hook<object>` | Runs once per successful fetch, not for Query.set.                                                                                                                                          |
| `onFailure?` | `Hook<object>` | Runs once per failed fetch, after `retry`.                                                                                                                                                  |
| `onSettled?` | `Hook<object>` | Runs once per fetch that succeeds or fails, after `onSuccess` or `onFailure`. None of the hooks run for a fetch that was interrupted (replaced by a refetch, reset, collected or disposed). |

### QueryClient.QueryDefaults

Options every query takes, set for all of them in `QueriesOptions.defaults`. A query's own options ([`Query.Options`](https://effetch-query.monarcode.dev/docs/reference/query#options)) extend these, with `E` its error type.

| Prop                  | Type     | Description                                                                                                                                                                                                                                                                                                             |
| --------------------- | -------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `staleTime?`          | `union`  | How long a success counts as fresh. Default: 0, stale at once.                                                                                                                                                                                                                                                          |
| `retry?`              | `object` | Retries a failed fetch on this schedule, which gets each failure. Defects aren't retried. Default: no retries.                                                                                                                                                                                                          |
| `refetchOnMount?`     | `union`  | If true, refetches a stale query when a component starts using it. Default: `true`.                                                                                                                                                                                                                                     |
| `retryOnMount?`       | `union`  | If true, refetches a failed query when a component starts using it, however recent the failure. A suspense reader (React's `useSuspenseQuery`) of a failure with no earlier value throws it to an error boundary instead, so it never starts using the query to retry it (see `useResetQueryFailure`). Default: `true`. |
| `refetchOnFocus?`     | `union`  | If true, refetches a stale query in use when the app regains focus (CommonOptions.signals). Default: `true`.                                                                                                                                                                                                            |
| `refetchOnReconnect?` | `union`  | If true, refetches a stale query in use when the device reconnects (CommonOptions.signals). Default: `true`.                                                                                                                                                                                                            |
| `refetchInterval?`    | `union`  | The interval at which a query in use refetches. A tick that finds a fetch in progress doesn't start another. Polling pauses while nothing uses the query and resumes when something starts using it. Default: no polling.                                                                                               |

### QueryClient.QueryFailed

What `QueriesOptions.onFailure` receives.

| Prop    | Type     | Description                          |
| ------- | -------- | ------------------------------------ |
| `key`   | `Key`    | The query's key.                     |
| `cause` | `object` | Why the fetch failed, after `retry`. |

### QueryClient.QuerySettled

What `QueriesOptions.onSettled` receives.

| Prop   | Type                     | Description                         |
| ------ | ------------------------ | ----------------------------------- |
| `key`  | `Key`                    | The query's key.                    |
| `exit` | `Exit<unknown, unknown>` | How the fetch ended, after `retry`. |

### QueryClient.QuerySucceeded

What `QueriesOptions.onSuccess` receives.

| Prop    | Type      | Description        |
| ------- | --------- | ------------------ |
| `key`   | `Key`     | The query's key.   |
| `value` | `unknown` | The fetched value. |

## Keep copies in sync

Guide: [Keep copies in sync](https://effetch-query.monarcode.dev/docs/cache/entity-sync).

### QueryClient.EntitiesOptions

The `entities` group of [`Options`](https://effetch-query.monarcode.dev/docs/reference/query-client#options): entities whose copies a fetch keeps in sync across the cache.

| Prop    | Type    | Description                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| ------- | ------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `sync?` | `array` | Entities kept in sync: when a query's fetch succeeds, each copy of these entities in its value goes over the other cached copies with the same id, in every query whose `schema` holds the entity. A copy another query holds that is newer comes into the fetched value instead. So a details refetch updates every list row of that record, and a list fetch updates the cached details, with no other fetch. - **Newer wins.** A copy is as new as the fetch attempt it came from, by when that attempt started: a slow response that lands after a newer one doesn't overwrite it, and the query that fetched it shows the newer copy instead. A refetch of an infinite query dates each page by its own attempt. Its next page is new, and only that page spreads: the pages it already had keep their age. A copy a query read from another (`ctx.result`) keeps that query's age, and a value from the server (`hydrate`) is older than any fetch. - **Only fetched copies spread.** A copy a write changed (`Query.set`, `Query.update`, Entity.set, Entity.update, a `live` push) counts as newer than every fetch already in flight, so none syncs over it. But a sync doesn't copy it to other queries: an entity write already reached every query that held it, and an optimistic one may be rolled back. - **Only fetches sync.** Writes, `live` pushes and stream queries' elements don't, so a sync never starts another sync. A sync doesn't write the queries the fetch read through `ctx.result`, so a fetch doesn't start itself again. A query that reads a written query through `ctx.result` refetches, as after any write to it. - **Ages kept.** A query written by a sync keeps its own age and staleness, as with Entity.update. Queries that are invalidated, failed, not cached or that opted out (`entities: { sync: false }`) are neither read nor written, and a query that doesn't hold an id doesn't gain it. A copy equal to the newer one (`Equal.equals`) isn't written. - **Optimistic writes.** A sync replaces a copy a mutation's `optimistic` changed when its fetch started later. If the mutation then fails, its rollback puts the old value back and the synced copy over it again, unless the query has fetched since. - **Cost.** Each fetch of a query that holds a synced entity reads every cached query that holds it, once per entity. For an entity in many large lists, opt out the queries that don't need it. - **Errors.** An `id` that throws is logged with `Effect.logError`; the fetch keeps its value and nothing is written. A listener that throws as a query is written is logged too. The other copies are written as the fetch settles. Default: none. |

## Use the cache outside Effect

Guide: [Read and write outside Effect](https://effetch-query.monarcode.dev/docs/cache#read-and-write-outside-effect).

### QueryClient.get

Returns a query's cached value in `client`, if it has one, outside Effect: TanStack's `queryClient.getQueryData`. It reads as [`Query.get`](https://effetch-query.monarcode.dev/docs/reference/query#get) does, without fetching, for code that can't wait for a promise, such as a form listener. Inside Effect, use [`Query.get`](https://effetch-query.monarcode.dev/docs/reference/query#get).

## Send the cache

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

### QueryClient.dehydrate

Reads a client's cache to send to the browser, for server rendering, as TanStack's `dehydrate`. Load what the page needs first ([`Query.prefetch`](https://effetch-query.monarcode.dev/docs/reference/query#prefetch) through `QueryClient.runPromise`), then send the result with the page and load it with [`hydrate`](https://effetch-query.monarcode.dev/docs/reference/query-client#hydrate) (or `HydrationBoundary` from `@monarcode/effetch-query/react`).

Only queries with a `schema` are sent, encoded with it, timestamp included, so a query stays fresh in the browser as long as it would on the server. It reads without fetching: a stale query is sent as it is. Values a schema can't encode are left out.

Throws a `NonJsonKeyError` for a key that isn't JSON, a `DuplicateQueryKeyError` when two queries it sends have one key, and a `Query.KeyHoldsTargetError` when `queries` is a key that holds a query, a family or a group.

### QueryClient.DuplicateQueryKeyError

Thrown by `QueryClient.dehydrate` when two cached queries it would send have one key: two definitions with the same key, such as two `api.query` of one Effetch endpoint. The browser finds a query by its key, so it couldn't tell them apart. Give one of them another key (an Effetch builder takes a `key` prefix).

### QueryClient.NonJsonKeyError

Thrown when a query key has to become a string, to send a query from the server to the browser, and a segment isn't JSON: a `Date`, a class instance, `undefined` in an array, `NaN` or `Infinity`, a function, a `bigint` or a symbol. Keys of queries that cross the wire hold only strings, finite numbers, booleans, `null`, and arrays and plain objects of them (`undefined` properties are dropped, as `JSON.stringify` drops them).

### QueryClient.DehydratedState

A client's cache as `dehydrate` sends it: Effect's `Hydration` format, so a framework's serializer carries it as it carries any atom state. Its values are JSON. With `pending: "promise"` ([`DehydrateOptions`](https://effetch-query.monarcode.dev/docs/reference/query-client#dehydrateoptions)), a query still loading carries a promise of its result, which only streaming serializers (React's, TanStack Start's, React Router's) can send.

### QueryClient.DehydrateOptions

Options for [`dehydrate`](https://effetch-query.monarcode.dev/docs/reference/query-client#dehydrate).

| Prop        | Type    | Description                                                                                                                                                                                                                                          |
| ----------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `queries?`  | `union` | A target: only the queries it matches are sent, as Query.invalidate matches them. Default: every query.                                                                                                                                              |
| `pending?`  | `union` | A query still loading, with nothing to show yet: `"promise"` sends a promise of its result, for streaming server rendering, and the browser waits for it instead of fetching; `"omit"` leaves it out, and the browser fetches it. Default: `"omit"`. |
| `failures?` | `union` | A failed query: `"include"` sends it with its error, encoded with the query's `schema.error` (defects as `Schema.Defect`); `"omit"` leaves it out, so the browser fetches it again and server errors never reach the page. Default: `"omit"`.        |

## Load the cache in the browser

Guide: [3. Load the cache in the browser](https://effetch-query.monarcode.dev/docs/server-rendering#3-load-the-cache-in-the-browser).

### QueryClient.hydrate

Loads a cache [`dehydrate`](https://effetch-query.monarcode.dev/docs/reference/query-client#dehydrate) sent into a client, as TanStack's `hydrate`. A query that isn't cached shows its value the first time it's read, without fetching, and refetches once it's stale. A cached query takes it only if it's newer than the last data it has. A query the server was still loading waits for its result instead of fetching.

Values its schema can't decode are dropped, and the query fetches. State from Effect's own `Hydration.dehydrate`, for other atoms, is loaded too.

## Client members

Guide: [Dispose a client](https://effetch-query.monarcode.dev/docs/client#dispose-a-client).

### QueryClient.disposeAfter

Returns `response` with its body wrapped so that `client` is disposed once the body has been sent: when it ends, fails, or the reader cancels it (a client that disconnects). A response with no body disposes the client at once. Use it for a client made per request on a server that answers with a streamed `Response`, where the request's handler returns before its streamed results are sent: React Router's middleware, Hono, `Bun.serve`, `Deno.serve`.

Send the response it returns: one that's discarded is never read, so the client is never disposed. Only the status, status text and headers are kept, not a runtime's own options (Cloudflare's `encodeBody`, say), and the body goes out as a stream, so a fixed body loses the length the runtime would have sent. A body already read or locked throws, and the client is disposed all the same. A failed `QueryClient.dispose` is logged with `console.error`, not thrown.

The core uses `ReadableStream` and `Response` only when this is called, so it still loads where they don't exist, such as React Native.