# normalized-react-query
Type-safe TanStack Query definitions that pair each key with its fetcher, and link related queries so they prefetch together.
[](https://www.npmjs.com/package/normalized-react-query)
[](https://github.com/JacobLey/leyman/blob/main/tools/normalized-react-query/LICENSE)
[TanStack Query](https://tanstack.com/query/latest) caches each API call under a key (like `['users', 'get', 123]`) that you pair with the function that fetches it. Nothing checks that pairing, though. Two calls can share a key but expect different data, and the second one silently gets the first one's cached result, with the wrong type. Or two calls can use different keys for the same data, and both fetch it.
`normalized-react-query` has you define each query once, as a `resource()` that pairs the key with its fetcher, and reuse it everywhere. Call sites pass typed params (`{ id: 123 }`) rather than building key arrays, and reads, writes and invalidation (`setQueryData`, `invalidateQuery`, …) are typed to the resource's data. Caching, refetching and subscriptions are still TanStack's.
Related data (a book's author, every user on a list page) tends to load in a waterfall, since the child's request can't start until the parent's data has loaded and the child has rendered. `.propagate()` declares those relationships next to the query, and the linked queries start prefetching as soon as the parent loads. For server rendering, `.query(client, params, { awaitLinks: true })` loads a query and everything it links to, ready to dehydrate.
Each of TanStack's hooks has a version here, in plain, suspense, nullable (`skipToken`), infinite and prefetched variants.
If you only want to share a key and fetcher between call sites, without the typed cache helpers or linked queries, TanStack's own [`queryOptions`](https://tanstack.com/query/latest/docs/framework/react/guides/query-options) covers that.
Guides and the full reference are on the [docs site](https://jacobley.github.io/leyman/packages/normalized-react-query/). For the full motivation, see [WHY-NORMALIZED-REACT-QUERY.md](https://github.com/JacobLey/leyman/blob/main/tools/normalized-react-query/WHY-NORMALIZED-REACT-QUERY.md).
## Contents
- [Install](#install)
- [Example](#example)
- [Usage](#usage)
- [API](#api)
- [resource](#resourceparams)
- [infinite](#infiniteparams)
- [Hooks](#hooks)
- [Linked](#linked)
- [Types](#types)
- [QueryData](#querydatat)
- [QueryParams](#queryparamst)
- [QueryKey](#querykeyt)
- [LinkOf](#linkoft)
- [Compared to alternatives](#compared-to-alternatives)
- [Also See](#also-see)
## Install
```sh
npm i normalized-react-query @tanstack/react-query react
```
`@tanstack/react-query` (`^5.104.3`) and `react` (`^18 || ^19`) are required peer dependencies. Requires Node.js 22.12 or later (`engines`).
## Example
```ts
import type { QueryClient, QueryKey } from '@tanstack/react-query';
import {
resource,
infinite,
useNormalizedQuery,
useNormalizedInfiniteQuery,
type QueryData,
type QueryParams,
} from 'normalized-react-query';
import { getUser, listUsers } from './api/users.js';
// Define a resource once — key and queryFn are always paired together.
const fetchUser = resource<{ id: number }, User>({
key: ({ id }) => ['users', 'get', id],
queryFn: ({ params: { id } }) => getUser(id),
});
// Whenever a page of users loads, prefetch each user's detail query.
const listUsersInfinite = infinite({
key: ['users', 'list'],
getInitialPageParam: 0,
getNextPageParam: ({ lastPage, lastPageParam }) =>
lastPage.length ? lastPageParam + 1 : undefined,
queryFn: ({ pageParam }) => listUsers(pageParam),
}).propagate(({ page }) =>
page.map(user => ({
...user,
detail: fetchUser.link({ id: user.id }),
}))
);
const useExample = (queryClient: QueryClient) => {
// All three refer to the same cache entry — no collision, no double-fetch.
const first = useNormalizedQuery(fetchUser, { id: 123 });
const second = useNormalizedQuery(fetchUser, { id: 123 }); // served from cache
const third = useNormalizedQuery(fetchUser, { id: 456 }); // separate entry
const list = useNormalizedInfiniteQuery(listUsersInfinite, undefined);
};
```
## Usage
`normalized-react-query` is an ESM module. It must be `import`ed. To load from a CJS module, use dynamic import: `const { resource } = await import('normalized-react-query');`.
This package enforces typing and structure, and leaves all caching, revalidation and subscription logic to React Query.
Instances created by `resource()` and `infinite()` are meant to be singletons, created once and imported everywhere. The functional constructors (`resource`, `infinite`) are the primary API. The underlying `Resource` and `Infinite` classes are also exported as types for use in type annotations. `Linked` is exported as a type too; [`LinkOf`](#linkoft) fills in its generics from a resource.
A resource that takes no params uses `void` as its `TParams` and a fixed `key` (`resource({ key: ['settings'], ... })`); hooks and cache methods then take `undefined` as the params.
Links are not stored in the cache. It holds the plain `queryFn` data, and `propagate` runs again whenever data is read (like a `select`), which keeps the cache serializable for SSR. Cache methods such as `setQueryData` therefore take the original data, not the propagated data.
## API
### `resource(params)`
Creates a type-safe, singleton reference to a non-paginated query. The key and query function are defined together and reused at every call site.
**Parameters**
| Parameter | Type | Default | Description |
| ---------------- | -------------------------------------------------------------------------------------------------- | ------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `params.key` | `TQueryKey \| ((params: TParams) => TQueryKey)` | — | Required. A static key or function computing the key from params. |
| `params.queryFn` | `(options: QueryFunctionContextWithParams, queryClient?) => Promise \| TData` | — | Required. The cached query function. Receives the params as `options.params`, plus standard TanStack context (`signal`, `queryKey`, …). |
Type parameters are inferred from `key` and `queryFn`, or given explicitly as `resource(...)`.
**Returns** `Resource` — a resource instance.
#### `Resource` instance methods
All methods that interact with the cache accept `queryClient` as the first argument and `params` as the second.
##### `.getKey(params): TQueryKey`
Returns the computed query key for the given params.
##### `.getParams(params): TParams`
Returns `params` unchanged. Useful for checking params against the resource's type before storing them for later.
##### `.getQueryFn(params): QueryFn`
Returns the query function bound to the given params, suitable for passing to TanStack directly.
##### `.getUseQueryOptions(queryClient, params | skipToken, options?)`
Returns options ready to spread into `useQuery` or `useQueries`. Supports `skipToken` to disable the query.
##### `.getUseSuspenseQueryOptions(queryClient, params, options?)`
Returns options ready to spread into `useSuspenseQuery` or `useSuspenseQueries`.
##### `.query(queryClient, params, options?): Promise`
Returns fresh cached data, or fetches it, like `queryClient.query`. Triggers propagation to downstream linked resources, which load in the background. Accepts every `queryClient.query` option besides the key and query function, plus:
- `select`: transforms the propagated data this call resolves with, without affecting the cache.
- `awaitLinks`: also waits for linked resources to load, and rejects if any fail (unless the link sets `isolateErrors`).
To load everything a server-side render needs, pass `{ staleTime: 'static', awaitLinks: true }`, so cached data is used as it is, and every link is loaded.
##### `.fetchQuery(queryClient, params, options?): Promise`
**Deprecated:** use `.query()`. Fetches (or reads from cache) and returns data. Triggers propagation to downstream linked resources.
##### `.prefetchQuery(queryClient, params, options?): Promise`
Loads data for someone else to use, like `.query()` but without throwing (the promise resolves even if the fetch fails). Accepts the options of `.query()` besides `select`. Returns a `Linked` reference usable with prefetched hooks.
##### `.ensureQueryData(queryClient, params, options?): Promise`
**Deprecated:** use `.query()` with `{ staleTime: 'static', awaitLinks: true }`. Returns stale cached data or fetches fresh data. Waits for all downstream propagated links to resolve.
##### `.setQueryData(queryClient, params, updater, options?): TData | undefined`
Sets data directly in the cache. The updater can be a value or a callback receiving the current cached value.
##### `.populate(queryClient, params, updater, options?): TParams`
Calls `setQueryData` and returns the params. Useful for chaining, since the returned params can be passed directly to hooks.
##### `.link(params, options?): Linked`
Must be called inside a `propagate` callback. Triggers a prefetch of this resource and returns a `Linked` reference for downstream hooks. Throws an `Error` (`Cannot call \`link()\` outside of \`propagate\``) if called outside of `propagate`. Linking the same query twice is safe.
`options` are the options of `.prefetchQuery()`, plus `isolateErrors`. When it's `true`, a failure of this link does not fail a parent loaded with `awaitLinks`.
##### `.propagate(map): Resource`
Attaches a transformation that runs after the query resolves. Inside `map`, call `.link()` on other resources to trigger downstream prefetches. Returns a new `Resource` with the updated propagated type.
##### `.invalidateQuery(queryClient, params, filters?, options?): Promise`
Invalidates the exact query entry for the given params.
##### `.refetchQuery(queryClient, params, filters?, options?): Promise`
Refetches the exact query entry for the given params.
##### `.cancelQuery(queryClient, params, filters?, options?): Promise`
Cancels the in-flight query for the given params.
##### `.removeQuery(queryClient, params, filters?): void`
Removes the query entry from cache.
##### `.resetQuery(queryClient, params, filters?, options?): Promise`
Resets the query to its initial state.
##### `.getQueryData(queryClient, params): TData | undefined`
Returns cached data without triggering a fetch.
##### `.getQueryState(queryClient, params): QueryState | undefined`
Returns the full TanStack query state object.
##### `.getCachedQuery(queryClient, params, filters?): Query | undefined`
Returns the internal TanStack `Query` instance.
##### `.isFetching(queryClient, params, filters?): boolean`
Returns `true` if a fetch is currently in flight for this exact query.
##### `.hasData(queryClient, params): boolean`
Returns `true` if any data is present in cache (regardless of staleness).
##### `.hasState(queryClient, params): boolean`
Returns `true` if a query state entry exists (whether fetching, stale, or idle).
---
### `infinite(params)`
Creates a type-safe, singleton reference to an infinite (paginated) query, backed by TanStack's infinite queries. Like `resource`, it supports `.propagate()`, so each loaded page can link to other resources.
**Parameters**
| Parameter | Type | Default | Description |
| ----------------------------- | -------------------------------------------------------------------------------------------------------------- | ----------- | ------------------------------------------------------------------------------------------ |
| `params.key` | `TQueryKey \| ((params: TParams) => TQueryKey)` | — | Required. A static key or function computing the key from params. |
| `params.queryFn` | `(options: QueryFunctionContextWithParams, queryClient?) => Promise \| TData` | — | Required. Called once per page load. |
| `params.getInitialPageParam` | `TPageParam \| ((params: TParams) => TPageParam)` | — | Required. The page param used to fetch the first page. |
| `params.getNextPageParam` | `(params: { lastPage, allPages, lastPageParam, allPageParams }) => TPageParam \| null \| undefined` | — | Required. Returns the next page param, or `null`/`undefined` when there are no more pages. |
| `params.getPreviousPageParam` | `(params: { firstPage, allPages, firstPageParam, allPageParams }) => TPageParam \| null \| undefined` | `undefined` | Optional. Enables backwards pagination. |
**Returns** `Infinite` — an infinite instance.
#### `Infinite` instance methods
`Infinite` extends `Queryable` and shares `getKey`, `getParams`, `invalidateQuery`, `refetchQuery`, `cancelQuery`, `removeQuery`, `resetQuery`, `getQueryData`, `getQueryState`, `getCachedQuery`, `isFetching`, `hasData`, and `hasState` with `Resource`.
##### `.getInitialPageParam(params): TPageParam`
Returns the initial page param for the given query params.
##### `.getGetNextPageParam(params): GetNextPageParamFunction`
Returns the `getNextPageParam` callback bound to the given params.
##### `.getGetPreviousPageParam(params): GetPreviousPageParamFunction`
Returns the `getPreviousPageParam` callback bound to the given params.
##### `.getQueryFn(params): QueryFn`
Returns the page query function bound to the given params, without propagation, suitable for passing to TanStack directly.
##### `.getUseInfiniteQueryOptions(queryClient, params | skipToken, options?)`
Returns options ready to spread into `useInfiniteQuery`. Supports `skipToken`.
##### `.getUseSuspenseInfiniteQueryOptions(queryClient, params, options?)`
Returns options ready to spread into `useSuspenseInfiniteQuery`.
##### `.infiniteQuery(queryClient, params, options?): Promise>`
Like `.query()`, for every loaded page: wraps `queryClient.infiniteQuery`, and accepts the same `select` and `awaitLinks` options.
##### `.fetchInfiniteQuery(queryClient, params, options?): Promise>`
**Deprecated:** use `.infiniteQuery()`. Fetches all loaded pages and triggers propagation.
##### `.prefetchInfiniteQuery(queryClient, params, options?): Promise`
Loads data for someone else to use, like `.infiniteQuery()` but without throwing. Returns a `Linked` reference.
##### `.ensureInfiniteQueryData(queryClient, params, options?): Promise>`
**Deprecated:** use `.infiniteQuery()` with `{ staleTime: 'static', awaitLinks: true }`. Returns stale or fresh data and waits for all propagated links to resolve.
##### `.setInfiniteQueryData(queryClient, params, updater, options?): InfiniteData | undefined`
Sets paginated data directly in the cache.
##### `.getInfiniteQueryData(queryClient, params): InfiniteData | undefined`
Alias of `.getQueryData()`, named to match `.setInfiniteQueryData()`.
##### `.populate(queryClient, params, updater, options?): TParams`
Calls `setInfiniteQueryData` and returns the params.
##### `.link(params, options?): Linked`
Must be called inside a `propagate` callback. Triggers a prefetch and returns a `Linked` reference. Throws if called outside of `propagate`.
##### `.propagate(map): Infinite`
Attaches a per-page transformation. The `map` callback receives `{ page, pageParam }` and may call `.link()` on other resources. Returns a new `Infinite` with the updated propagated type.
---
### Hooks
All hooks wrap their TanStack counterparts with type-safe resource/infinite instances. The `key` and `queryFn` are derived from the resource, so don't pass them yourself. `options` are the TanStack hook's options minus `queryKey` and `queryFn`; `select` receives the propagated data (the result of `.propagate()`, with `Linked` references), not the cached data.
Like TanStack's hooks, each hook stays on the query client it first renders with. The `useNormalizedPrefetched*` hooks read the link's client, and the context client while they have no link (`null` or `skipToken`). A hook that renders without a link first therefore only accepts links on the context client, and needs a `QueryClientProvider` to accept any link at all. Given a link on any other client, it throws, rather than reading a different cache. [TanStack/query#12257](https://github.com/TanStack/query/pull/12257) would let hooks follow a client change, and remove this restriction.
#### `useNormalizedQuery(res, params | skipToken, options?, queryClient?)`
Wraps `useQuery`. Pass `skipToken` as `params` to disable the query.
#### `useNormalizedSuspenseQuery(res, params, options?, queryClient?)`
Wraps `useSuspenseQuery`.
#### `useNormalizedNullableSuspenseQuery(res, params | skipToken, options?, queryClient?)`
Wraps `useSuspenseQuery` with `skipToken` support. Returns `null` when `skipToken` is passed.
#### `useNormalizedPrefetchQuery(res, params, options?, queryClient?): Linked`
Wraps `usePrefetchQuery`. Triggers a prefetch on first render and returns a `Linked` reference for use with prefetched hooks.
#### `useNormalizedPrefetchedQuery(linked | skipToken | null, options?)`
Wraps `useQuery` for data that has already been prefetched via `prefetchQuery` or `useNormalizedPrefetchQuery`.
#### `useNormalizedPrefetchedSuspenseQuery(linked, options?)`
Wraps `useSuspenseQuery` for prefetched data.
#### `useNormalizedNullablePrefetchedSuspenseQuery(linked | skipToken | null, options?)`
Wraps `useSuspenseQuery` with `skipToken` support for prefetched data. Returns `null` when disabled.
#### `useNormalizedInfiniteQuery(inf, params | skipToken, options?, queryClient?)`
Wraps `useInfiniteQuery`. Pass `skipToken` as `params` to disable.
#### `useNormalizedSuspenseInfiniteQuery(inf, params, options?, queryClient?)`
Wraps `useSuspenseInfiniteQuery`.
#### `useNormalizedNullableSuspenseInfiniteQuery(inf, params | skipToken, options?, queryClient?)`
Wraps `useSuspenseInfiniteQuery` with `skipToken` support. Returns `null` when `skipToken` is passed.
#### `useNormalizedPrefetchInfiniteQuery(inf, params, options?, queryClient?): Linked`
Wraps `usePrefetchInfiniteQuery`. Triggers a prefetch on first render and returns a `Linked` reference for use with prefetched hooks.
#### `useNormalizedPrefetchedInfiniteQuery(linked | skipToken | null, options?)`
Wraps `useInfiniteQuery` for data that has already been prefetched via `prefetchInfiniteQuery` or `useNormalizedPrefetchInfiniteQuery`.
#### `useNormalizedPrefetchedSuspenseInfiniteQuery(linked, options?)`
Wraps `useSuspenseInfiniteQuery` for prefetched infinite data.
#### `useNormalizedNullablePrefetchedSuspenseInfiniteQuery(linked | skipToken | null, options?)`
Wraps `useSuspenseInfiniteQuery` with `skipToken` support for prefetched infinite data. Returns `null` when disabled.
---
### `Linked`
A `Linked` (not exported by name, see [Usage](#usage)) is a reference to a specific query that has been (or is being) prefetched. It is produced by `.prefetchQuery()`, `.prefetchInfiniteQuery()`, `.link()`, `useNormalizedPrefetchQuery()` and `useNormalizedPrefetchInfiniteQuery()`.
Pass `Linked` instances to the `useNormalizedPrefetched*` hooks to subscribe to their data.
#### `.getQueryable(): TQueryable`
Returns the resource or infinite instance.
#### `.getParams(): TParams`
Returns the params that were used to prefetch.
#### `.getQueryClient(): QueryClient`
Returns the query client associated with the prefetch.
## Types
### `QueryData`
Extracts the cached data type (`TData`) from a `Resource` or `Infinite` instance type.
```ts
type UserData = QueryData; // User
```
### `QueryParams`
Extracts the params type from a `Resource` or `Infinite` instance type.
```ts
type UserParams = QueryParams; // { id: number }
```
### `QueryKey`
Extracts the query key type from a `Resource` or `Infinite` instance type.
### `LinkOf`
Extracts the `Linked` type for a given `Resource` or `Infinite` instance type. Useful for typing function parameters that accept a prefetched reference.
```ts
type UserLink = LinkOf;
// Linked<{ id: number }, readonly unknown[], User, Resource<...>>
```
## Compared to alternatives
- TanStack's own [`queryOptions`](https://tanstack.com/query/latest/docs/framework/react/guides/query-options) also pairs a key with its fetcher, but per call site, without params-typed cache helpers or linked prefetching.
- [@lukemorales/query-key-factory](https://www.npmjs.com/package/@lukemorales/query-key-factory) organizes keys (and optionally fetchers) into a typed tree. It doesn't link queries or wrap the hooks.
## Also See
- [`@tanstack/react-query`](https://tanstack.com/query/latest) — the underlying query library this package wraps
- [WHY-NORMALIZED-REACT-QUERY.md](https://github.com/JacobLey/leyman/blob/main/tools/normalized-react-query/WHY-NORMALIZED-REACT-QUERY.md) — motivation: the key/function pairing problem, and request waterfalls