# QueryClient (https://0758e0c7.effetch-query.pages.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 one has
the first paragraph of its docs, and what it needs and how it fails; your
editor shows the rest, with an example, when you hover the name.

## The client

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

### QueryClient.make

Creates a [`QueryClient`](https://0758e0c7.effetch-query.pages.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://0758e0c7.effetch-query.pages.dev/docs/reference/query-client#runtimeoptions)). With no services declared in [`Register`](https://0758e0c7.effetch-query.pages.dev/docs/reference/query-client#register), the options can be left out ([`OptionalOptions`](https://0758e0c7.effetch-query.pages.dev/docs/reference/query-client#optionaloptions)).

### QueryClient.QueryClient

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://0758e0c7.effetch-query.pages.dev/docs/reference/query-client#layer).

### QueryClient.CommonOptions

The [`Options`](https://0758e0c7.effetch-query.pages.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://0758e0c7.effetch-query.pages.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://0758e0c7.effetch-query.pages.dev/docs/reference/query-client#make) and [`layer`](https://0758e0c7.effetch-query.pages.dev/docs/reference/query-client#layer). With no services declared in [`Register`](https://0758e0c7.effetch-query.pages.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://0758e0c7.effetch-query.pages.dev/docs/reference/query-client#make) and [`layer`](https://0758e0c7.effetch-query.pages.dev/docs/reference/query-client#layer): your services, as a layer ([`LayerOptions`](https://0758e0c7.effetch-query.pages.dev/docs/reference/query-client#layeroptions)) or a runtime that already provides them ([`RuntimeOptions`](https://0758e0c7.effetch-query.pages.dev/docs/reference/query-client#runtimeoptions)), with the [`CommonOptions`](https://0758e0c7.effetch-query.pages.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://0758e0c7.effetch-query.pages.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.

### QueryClient.Requirements

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

### QueryClient.RuntimeOptions

[`Options`](https://0758e0c7.effetch-query.pages.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.

| 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://0758e0c7.effetch-query.pages.dev/docs/reference/query-client#register), or `never` without the augmentation.

## Testing

Guide: [Testing](https://0758e0c7.effetch-query.pages.dev/docs/testing).

### QueryClient.layer

Creates a [`QueryClient`](https://0758e0c7.effetch-query.pages.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.

## Defaults and app-wide hooks

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

### QueryClient.Hook

An app-wide hook in [`QueriesOptions`](https://0758e0c7.effetch-query.pages.dev/docs/reference/query-client#queriesoptions) or [`MutationsOptions`](https://0758e0c7.effetch-query.pages.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.

### QueryClient.MutationFailed

What `MutationsOptions.onFailure` receives.

### QueryClient.MutationSettled

What `MutationsOptions.onSettled` receives.

### QueryClient.MutationsOptions

The `mutations` group of [`Options`](https://0758e0c7.effetch-query.pages.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.

### QueryClient.MutationSucceeded

What `MutationsOptions.onSuccess` receives.

### QueryClient.QueriesOptions

The `queries` group of [`Options`](https://0758e0c7.effetch-query.pages.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://0758e0c7.effetch-query.pages.dev/docs/reference/query#options)) extend these, with `E` its error type.

### QueryClient.QueryFailed

What `QueriesOptions.onFailure` receives.

### QueryClient.QuerySettled

What `QueriesOptions.onSettled` receives.

### QueryClient.QuerySucceeded

What `QueriesOptions.onSuccess` receives.

## Keep copies in sync

Guide: [Keep copies in sync](https://0758e0c7.effetch-query.pages.dev/docs/mutations/entity-sync).

### QueryClient.EntitiesOptions

The `entities` group of [`Options`](https://0758e0c7.effetch-query.pages.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: [Use the cache outside Effect](https://0758e0c7.effetch-query.pages.dev/docs/cache/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://0758e0c7.effetch-query.pages.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://0758e0c7.effetch-query.pages.dev/docs/reference/query#get).

## Send the cache

Guide: [Send the cache](https://0758e0c7.effetch-query.pages.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://0758e0c7.effetch-query.pages.dev/docs/reference/query#prefetch) through `QueryClient.runPromise`), then send the result with the page and load it with [`hydrate`](https://0758e0c7.effetch-query.pages.dev/docs/reference/query-client#hydrate) (or `HydrationBoundary` from `@monarcode/effetch-query/react`).

Throws a `NonJsonKeyError` for a key that isn't JSON, and a `DuplicateQueryKeyError` when two queries it sends have one key.

### 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://0758e0c7.effetch-query.pages.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://0758e0c7.effetch-query.pages.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: [Load the cache in the browser](https://0758e0c7.effetch-query.pages.dev/docs/server-rendering/hydrate).

### QueryClient.hydrate

Loads a cache [`dehydrate`](https://0758e0c7.effetch-query.pages.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.

## Client members

Guide: [Client members](https://0758e0c7.effetch-query.pages.dev/docs/client/members).

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

## Related pages

- [Entry points](https://0758e0c7.effetch-query.pages.dev/docs/reference): what each entry point exports.
- [`@monarcode/effetch-query`](https://0758e0c7.effetch-query.pages.dev/docs/reference/core): the core entry point's namespaces and top-level names.
- [`Query`](https://0758e0c7.effetch-query.pages.dev/docs/reference/query): defining queries, keys and targets, and the cache from Effect.
- [`InfiniteQuery`](https://0758e0c7.effetch-query.pages.dev/docs/reference/infinite-query): queries that load a list one page at a time.
- [`Mutation`](https://0758e0c7.effetch-query.pages.dev/docs/reference/mutation): defining and running mutations.
- [`Entity`](https://0758e0c7.effetch-query.pages.dev/docs/reference/entity): records whose every cached copy a write updates.
- [`Signals`](https://0758e0c7.effetch-query.pages.dev/docs/reference/signals): where a client hears about focus and reconnects.
- [`@monarcode/effetch-query/react`](https://0758e0c7.effetch-query.pages.dev/docs/reference/react): the provider, the hooks and the boundaries.
- [`@monarcode/effetch-query/effetch`](https://0758e0c7.effetch-query.pages.dev/docs/reference/effetch): queries and mutations from Effetch endpoints.
- [`@monarcode/effetch-query/react-native`](https://0758e0c7.effetch-query.pages.dev/docs/reference/react-native): focus and online signals for React Native.
- [`@monarcode/effetch-query/react/tanstack-router`](https://0758e0c7.effetch-query.pages.dev/docs/reference/tanstack-router): connecting a client to TanStack Router and Start.