A typed, framework-agnostic query-key factory for TanStack Query v5, tested at run time with query-core's QueryClient and in a React Query app, and type-tested with React Query and Vue Query. Organise your query keys in scopes, get real queryOptions() objects back with DataTag-branded keys, and invalidate or update whole branches of the cache with typed helpers. It keeps the API of @lukemorales/query-key-factory: for most code, switching is an import change, and the migration notes list what behaves differently.
import { createQueryKeys, invalidateScope } from '@amjadiqbal/query-key-kit';
export const todos = createQueryKeys('todos', {
all: null,
detail: (id: number) => ({
queryKey: [id],
queryFn: () => api.getTodo(id),
staleTime: 30_000,
contextQueries: {
comments: { queryKey: null, queryFn: () => api.getComments(id) },
},
}),
list: (filters: TodoFilters) => ({
queryKey: [{ filters }],
queryFn: () => api.getTodos(filters),
}),
});
useQuery(todos.detail(1)); // key ['todos', 'detail', 1], data: Todo | undefined
useQuery(todos.detail(1)._ctx.comments); // key ['todos', 'detail', 1, 'comments']
queryClient.getQueryData(todos.detail(1).queryKey); // Todo | undefined, no cast
invalidateScope(queryClient, todos.list); // every todos.list(...) query
invalidateScope(queryClient, todos.detail(1)); // detail 1 and its comments
invalidateScope(queryClient, todos); // everything under 'todos'TanStack Query v5's queryOptions() already keeps a key and its fetcher together. What it does not give you is a key hierarchy: one place that says which keys exist, how they nest, and which partial key to pass when you invalidate. Teams write that by hand, or use @lukemorales/query-key-factory, which gets about 1.4 million downloads a month but has had no release since February 2024 and still has open v5 typing bugs.
query-key-kit is a maintained, v5-first take on the same idea:
- Returns real query options. Every entry produces what
queryOptions()produces: aDataTag-brandedqueryKey(sogetQueryData,setQueryDataandfetchQueryare typed) and aqueryFntyped against the full key. - Any query option on an entry.
staleTime,gcTime,placeholderData,initialData,select,meta,enabled,initialPageParam,getNextPageParam... are passed through unchanged. - Infinite queries.
pageParamis available inqueryFn, and an entry withinitialPageParamworks withuseInfiniteQueryandfetchInfiniteQuery. - Typed scope helpers.
invalidateScope,refetchScope,cancelScope,removeScope,getScopeDataandsetScopeDatatake any query node of the tree and pick the right partial key.getScopeDataandsetScopeDataknow the data type of every query they match. - Mutations.
createMutationKeyskeepsmutationFn's own type, souseMutationinfers variables and result. - Framework-agnostic. It depends only on
@tanstack/query-coretypes, so the same keys work with any adapter. Tested with@tanstack/react-queryand@tanstack/vue-query; Solid, Svelte and Angular Query share those core types but have no tests of their own yet. - Small. No runtime dependencies, ESM only,
"sideEffects": false. The 0.1.3 build is one 6.7 kB JavaScript file (2.1 kB gzipped).
npm install @amjadiqbal/query-key-kitYou also need TanStack Query v5 for your framework (for example @tanstack/react-query), which brings @tanstack/query-core. TypeScript 5.0 or newer: the built .d.ts is checked with TypeScript 5.0.4 against @tanstack/query-core 5.0.0 (newer query-core releases need TypeScript 5.4 or later for their own types), and the library is built and tested with TypeScript 7.0.
createQueryKeys(scope, schema) takes a scope name and an object of entries. Each entry is one of:
| Entry | Example | Produces |
|---|---|---|
null |
all: null |
{ queryKey: ['todos', 'all'] } |
| key tuple | count: ['total'] |
{ _def: ['todos', 'count'], queryKey: ['todos', 'count', 'total'] } |
| options object | stats: { queryKey: null, queryFn, staleTime } |
query options with key ['todos', 'stats'] |
| function | detail: (id: number) => ({ queryKey: [id], queryFn }) |
a function returning query options, with _def: ['todos', 'detail'] on the function |
An options object (returned directly or from a function) may contain:
queryKey: extra key parts appended to the entry's path, ornullfor none.queryFn: the fetcher. It receives the full key inctx.queryKey, plusctx.pageParamfor infinite queries.skipTokenworks.contextQueries: a nested schema whose keys extend this entry's key. They appear under_ctx.- Any other query option, passed through as is.
Names starting with _ are reserved for _def and _ctx, and are rejected at compile time and at run time.
// One file
export const queries = createQueryKeyStore({
users: null,
todos: {
detail: (id: number) => ({ queryKey: [id], queryFn: () => api.getTodo(id) }),
},
});
// Or one scope per feature, merged
export const queries = mergeQueryKeys(users, todos, todoMutations);
queries.todos.detail(1);mergeQueryKeys combines scopes that share a name, typically a query scope and a mutation scope. If two of them define the same entry name, it throws rather than letting one replace the other.
Give the entry initialPageParam and getNextPageParam. queryFn receives pageParam:
export const todos = createQueryKeys('todos', {
feed: (filters: TodoFilters) => ({
queryKey: [filters],
queryFn: ({ pageParam }: { pageParam: number }) => api.getPage(filters, pageParam),
initialPageParam: 0,
getNextPageParam: (last: Page) => last.nextCursor,
}),
});
useInfiniteQuery(todos.feed({ status: 'open' })); // data: InfiniteData<Page> | undefinedCallbacks inside an entry (getNextPageParam, select, placeholderData as a function) need their parameter annotated, because the entry is not tied to one query yet. Or add them at the call site, below.
Entries are plain objects, so spread them, directly or through the official helpers:
useQuery({ ...todos.detail(id), enabled: !!id, select: (todo) => todo.title });
const titleQuery = queryOptions({ ...todos.detail(id), select: (todo) => todo.title });
const feed = infiniteQueryOptions({ ...todos.feed(filters), maxPages: 3 });Don't wrap the entry itself in queryOptions() inside createQueryKeys: those options are typed for the inner key, and TanStack's hooks then reject the prefixed key.
Every node of the tree knows its partial key. Pass the node, not a hand-written array:
import { cancelScope, getScopeData, invalidateScope, setScopeData } from '@amjadiqbal/query-key-kit';
await invalidateScope(queryClient, todos); // ['todos']
await invalidateScope(queryClient, todos.list); // ['todos', 'list'], every filter
await invalidateScope(queryClient, todos.detail(1)); // ['todos', 'detail', 1] and its _ctx
await invalidateScope(queryClient, todos.detail(1), { exact: true }); // only that query
// Optimistic update of every cached list at once. `old` is Todo[] | undefined.
await cancelScope(queryClient, todos.list);
setScopeData(queryClient, todos.list, (old) => old?.map((t) => (t.id === id ? { ...t, done: true } : t)));
getScopeData(queryClient, todos.list); // Array<[QueryKey, Todo[] | undefined]>| Helper | Calls |
|---|---|
invalidateScope(client, node, filters?, options?) |
client.invalidateQueries |
refetchScope(client, node, filters?, options?) |
client.refetchQueries |
cancelScope(client, node, filters?, options?) |
client.cancelQueries |
removeScope(client, node, filters?) |
client.removeQueries |
getScopeData(client, node, filters?) |
client.getQueriesData, typed |
setScopeData(client, node, updater, filters?) |
client.setQueriesData, typed |
scopeKey(node) |
returns the partial key |
The partial key is queryKey for an entry or a called entry, and _def for a scope or a function entry. filters takes every query filter except queryKey (exact, type, stale, predicate, ...). client is typed as query-core's QueryClient (only the method each helper calls), so adapter clients that extend it are accepted; run-tested with query-core's and React Query's, type-tested with Vue Query's. Mutation entries, function mutation entries and scopes created with createMutationKeys are rejected at compile time and throw at run time (scopeKey and every helper), because a mutation key used as a query filter would match unrelated queries. The data type of a node is the union of every query its key matches, including context queries; it is unknown when a matched entry has no queryFn.
You can still use the keys directly: queryClient.invalidateQueries({ queryKey: todos.detail._def }).
export const todoMutations = createMutationKeys('todos', {
create: { mutationKey: null, mutationFn: (input: NewTodo) => api.createTodo(input) },
toggle: (id: number) => ({ mutationKey: [id], mutationFn: (done: boolean) => api.setDone(id, done) }),
});
const create = useMutation(todoMutations.create);
create.mutate({ title: 'Ship it' }); // variables typed from mutationFn
const toggle = useMutation({
...todoMutations.toggle(1),
onSuccess: () => invalidateScope(queryClient, todos.detail(1)),
});| Type | Gives |
|---|---|
inferQueryKeys<typeof todos> |
the key tree (queryKey, _def, _ctx) without functions or options |
inferQueryKeyStore<typeof queries> |
the same for a whole store |
inferQueryData<typeof todos.detail> |
the data of an entry (Todo) |
inferScopeData<typeof todos.detail> |
the data of every query under a node |
TypedUseQueryOptions<typeof todos.detail> |
observer options for custom hooks |
type Keys = inferQueryKeyStore<typeof queries>;
const fetchList = async (ctx: QueryFunctionContext<Keys['todos']['list']['queryKey']>) => {
const [, , { filters }] = ctx.queryKey; // typed
return api.getTodos(filters);
};-
Install and swap the import:
npm uninstall @lukemorales/query-key-factory && npm install @amjadiqbal/query-key-kitgrep -rl "@lukemorales/query-key-factory" src | xargs sed -i '' 's#@lukemorales/query-key-factory#@amjadiqbal/query-key-kit#g'
(On Linux, use
sed -iwithout the''.) -
Run your type checker.
createQueryKeys,createQueryKeyStore,mergeQueryKeys,createMutationKeys,inferQueryKeys,inferQueryKeyStoreandTypedUseQueryOptionskeep their names, and the keys they produce (queryKey,_def,_ctx) are the same. Then check the differences below, especially the first one: it changes runtime behaviour.
What changes:
- Options are kept (runtime change). lukemorales silently dropped everything except
queryKeyandqueryFn(its issues #83 and #85). HerestaleTime,placeholderData,initialDataand the rest reachuseQuery. If you added options that never took effect, they now do, so review them before switching. - Keys are
DataTag-branded, likequeryOptions().getQueryDatareturns your data type instead ofunknown. ctx.pageParamworks and infinite entries work withuseInfiniteQuery(#89, #73).- Mutation variables are typed from
mutationFn(#55). initialDatagives defined data fromuseQuery(#76).- Entries keep your declaration order instead of being sorted. Keys are unchanged.
- Objects have a normal prototype instead of
Object.create(null). inferQueryKeysreturns only keys (queryKey,_def,_ctx), not other options.TypedUseQueryOptions<Entry, Data>takes the same two type arguments, but is built on query-core'sQueryObserverOptionsinstead of React'sUseQueryOptions(the same options outside React-only ones such assuspense), and its error type isDefaultErrorinstead ofunknown.mergeQueryKeysthrows when two merged scopes define the same entry name; lukemorales let the later one win silently.
- Unit tests (Vitest) run every entry kind, context queries, stores, merging and mutations against a real
QueryClientfrom@tanstack/query-core: fetching with the full key, infinite queries with page params, and every scope helper against a filled cache. - Type tests (
expectTypeOf) coveruseQuery,useSuspenseQuery,useInfiniteQuery,useQueriesanduseMutationfrom@tanstack/react-query,useQueryfrom@tanstack/vue-query, spreading entries intoqueryOptions()/infiniteQueryOptions(),skipToken,initialData, and the compatibility types. - Declaration emit is checked: a module that exports its keys compiles with
declaration: true. - The library also type-checks against
@tanstack/query-core5.0.0, the lowest supported version. - The built
dist/index.d.tsis type-checked with TypeScript 5.0.4 against@tanstack/query-core5.0.0, withskipLibCheckoff so the.d.tsitself is checked (npm run typecheck:ts5). examples/reactcovers the main features:createQueryKeys(null, function and infinite entries,contextQueries,staleTime,placeholderData),createMutationKeys,mergeQueryKeys,inferQueryKeyStore,useQuery,useInfiniteQuery,useMutation,scopeKey,invalidateScope,cancelScope,setScopeData,getScopeDataand typedgetQueryData.npm run check:exampleinstalls the packed tarball into it and type-checks it. The rest (createQueryKeyStore,refetchScope,removeScope,TypedUseQueryOptions, the otherinfer*types,skipToken,initialData,useSuspenseQuery,useQueries) is covered by the unit and type tests only. Releases so far were also checked by hand in a browser with it, including a fresh install from npm.- Solid, Svelte and Angular Query rely on the shared query-core types and have no tests of their own yet.
- ๐ Bug or feature request: open an issue
- ๐ Security issue: please report privately via GitHub's security tab
Part of a family of open-source packages. See all of them.
| start-seo-kit | SEO for TanStack Start: meta tags, sitemaps, JSON-LD |
The API follows @lukemorales/query-key-factory by Luke Morales (MIT), which this package replaces. The code here is a new implementation for TanStack Query v5.
MIT. See LICENSE.md.