Svelte Query 06 ⚡ Type-Safe queryOptions & Key Factories
TanStack Query (often used as Svelte Query) relies entirely on query keys to manage caching, deduping, and invalidation. In growing applications, hardcoding these keys as disparate arrays across your codebase leads to “stringly-typed” maintenance nightmares, cache collisions, and fragmented logic. The solution is a combination of structured hierarchical key factories and the queryOptions helper, which couples the key definition directly with the data-fetching logic.
This chapter explores how to move away from manual array management toward a type-safe factory pattern. We will cover the implementation of key factories that enforce structure, the use of queryOptions to encapsulate the “what” and the “how” of a query, and strategies for leveraging these patterns to make your invalidation logic both predictable and efficient.
Key point: queryOptions ensures type-safe coupling of a query key and its fetcher function, while key factories provide a single source of truth for your cache hierarchy, enabling granular invalidation and preventing runtime errors caused by mismatched keys.
Why exists
The “stringly-typed” key problem. When query keys are defined as loose arrays scattered throughout the app, renaming an API endpoint or changing a parameter becomes a dangerous, error-prone task. Factories centralize these keys.
The cache collision risk. In large teams, it is easy for two different developers to create keys that overlap (e.g., ['user'] vs ['users']), leading to unexpected data sharing across features. Factories define the hierarchy explicitly.
The coupling difficulty. A query key is meaningless without its corresponding fetcher function. queryOptions forces these two to live together, ensuring that you never provide a key to a fetcher that doesn’t belong to it.
The invalidation complexity. Granular invalidation (e.g., “invalidate all users” vs “invalidate user 123”) requires strict key hierarchy. Factories make it trivial to define users.all and users.detail(id), allowing you to use queryClient.invalidateQueries({ queryKey: users.all() }) with full confidence.
The type-safety gap. Without queryOptions, TypeScript cannot easily infer the return type of a useQuery call based on the specific fetcher function passed to it. queryOptions restores this inference, providing full autocompletion for your resulting data.
a. The Key Factory Pattern
A key factory is a simple object or class containing functions that return arrays. The goal is to define the hierarchy such that you can easily group or isolate queries. The root keys go at the top, and specific resources are added as children.
// src/lib/query/userKeys.ts
export const userKeys = {
all: () => ['users'] as const,
list: (filters: { role: string }) => [...userKeys.all(), 'list', filters] as const,
detail: (id: string) => [...userKeys.all(), 'detail', id] as const,
};
By using as const, we ensure that the arrays are treated as tuples, which preserves the specific structure of the key for TypeScript. When you need to invalidate all users, you use userKeys.all(). When you need to invalidate a single user, you use userKeys.detail(id).
b. Coupling with queryOptions
The queryOptions helper is the bridge between your key factory and the queryFn. It provides a centralized configuration object that can be passed directly to useQuery, fetchQuery, or prefetchQuery. This eliminates the need to specify the queryKey and queryFn separately, preventing potential configuration mismatches.
// src/lib/query/userOptions.ts
import { queryOptions } from '@tanstack/svelte-query';
import { userKeys } from './userKeys';
export const userOptions = {
detail: (id: string) => queryOptions({
queryKey: userKeys.detail(id), // Links key factory
queryFn: () => fetchUser(id), // Links fetcher
staleTime: 1000 * 60 * 5, // Config persistence
})
};
When you use useQuery(userOptions.detail(id)) in your component, Svelte Query automatically knows that queryKey and queryFn are perfectly matched. If you later change the parameters of detail, the TypeScript compiler will immediately point out any call sites that need to be updated.
c. Advanced invalidation and prefetching
Factories make cross-component logic significantly cleaner. Because the factory is a centralized module, your mutation logic can import the factory to perform precise cache invalidations without knowing the implementation details of the fetchers.
// Inside a mutation or invalidation logic
import { useQueryClient } from '@tanstack/svelte-query';
import { userKeys } from './userKeys';
const queryClient = useQueryClient();
// Invalidate specific detail
queryClient.invalidateQueries({ queryKey: userKeys.detail(id) });
// Invalidate all lists
queryClient.invalidateQueries({ queryKey: userKeys.all() });
This structural discipline is the only way to manage large TanStack Query caches effectively. By strictly adhering to the hierarchy, you avoid “over-fetching” (invalidating more than you need) and “under-fetching” (keeping stale data around because the keys didn’t match).
Complete Example Session
// ============================================
// PART 1: DEFINING THE FACTORY
// ============================================
export const postKeys = {
all: () => ['posts'] as const,
list: (page: number) => [...postKeys.all(), 'list', page] as const,
detail: (id: string) => [...postKeys.all(), 'detail', id] as const
};
// ============================================
// PART 2: THE QUERY OPTIONS
// ============================================
export const postOptions = {
list: (page: number) => queryOptions({
queryKey: postKeys.list(page),
queryFn: () => fetchPosts(page)
})
};
// ============================================
// PART 3: USAGE IN COMPONENT
// ============================================
const query = createQuery(postOptions.list(page));
// ============================================
// PART 4: MUTATION & INVALIDATION
// ============================================
const queryClient = useQueryClient();
// invalidate specific page
queryClient.invalidateQueries({ queryKey: postKeys.list(1) });
// invalidate all posts
queryClient.invalidateQueries({ queryKey: postKeys.all() });
The example demonstrates the full flow: the definition of the hierarchical factory, the use of queryOptions to link logic, consumption in a component, and granular invalidation in a mutation handler.
Quick Reference
Factory Hierarchy Pattern
| Function | Output | Invalidation Scope |
|---|---|---|
.all() | ['root'] | Entire resource |
.list() | ['root', 'list', p] | All lists |
.detail() | ['root', 'detail', id] | Single item |
queryOptions Benefits
| Benefit | Description |
|---|---|
| Coupling | Key and Fn inseparable |
| Type Safety | Auto-inferred return data |
| Reusability | Same options for prefetch/query |
Best Practices
✅ Do This:
// Use as const for tuples
all: () => ['users'] as const; // ✅
// Always couple key with queryFn
queryOptions({ queryKey: key, queryFn: fn }); // ✅
// Nest keys via spread operator
list: (id) => [...all(), 'list', id]; // ✅
// Use options in prefetch
queryClient.prefetchQuery(userOptions.detail(id)); // ✅
❌ Don’t Do This:
// Don't define keys inline in useQuery
useQuery({ queryKey: ['users', id], queryFn: ... }); // ❌
// Don't mix raw arrays and factories
// Use the factory everywhere // ❌
// Don't omit the tuple constraint
all: () => ['users']; // missing 'as const' // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Mismatched keys | Inline definitions | Use factory exclusively |
| Invalidation miss | Key path changed | Update factory, not strings |
| Type errors | Lack of as const | Add as const to all keys |
| Refetch loop | queryFn reference unstable | Use queryOptions object |
Real-World Examples
1. Root Key
all: () => ['posts'] as const
2. Paginated List Key
list: (page) => [...posts.all(), 'list', page] as const
3. Detail Key
detail: (id) => [...posts.all(), 'detail', id] as const
4. Prefetching Option
queryClient.prefetchQuery(postOptions.list(1))
5. Mutation Invalidation
queryClient.invalidateQueries({ queryKey: postKeys.all() })
6. Custom Stale Time
staleTime: 1000 * 60
7. Dependent Query
enabled: !!id
8. Select Transformer
select: (data) => data.items
9. Infinite Query Option
queryKey: postKeys.list('infinite')
10. Type Inference
data: TData // inferred from queryOptions
Visual
The Factory Hierarchy
┌──────────────────────────────────────────────┐
│ ROOT: ['users'] │
│ │ │
│ ├─ LIST: ['users', 'list', filters] │
│ │ │
│ └─ DETAIL: ['users', 'detail', id] │
└──────────────────────────────────────────────┘
The QueryOptions Coupling
┌──────────────────────────────────────────────┐
│ queryOptions({ │
│ queryKey: ['users', 'detail', '1'], │
│ queryFn: () => fetchUser('1') │
│ }) │
│ │
│ Effect: These two are now a locked unit │
└──────────────────────────────────────────────┘
Invalidation Scope
┌──────────────────────────────────────────────┐
│ invalidate(userKeys.all()) │
│ └─ Clears: ['users'], ['users', 'list', 1], │
│ ['users', 'detail', 1] │
│ │
│ invalidate(userKeys.detail(1)) │
│ └─ Clears: ['users', 'detail', 1] ONLY │
└──────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Key Factory | Centralized array-generator |
queryOptions | Type-safe Key/Fn coupler |
| Invalidation | Hierarchical cache purging |
| Tuple Constraint | as const for strict keys |
Key takeaways:
- Use factory objects to define hierarchy. Every resource should have a root key factory that acts as the entry point for all derived sub-keys.
queryOptionsis non-negotiable for large apps. It enforces the coupling of keys and fetchers, which is the single most effective way to eliminate “missing key” or “wrong fetcher” bugs.- Granular invalidation relies on structure. You can only invalidate specific subsets of your cache if your keys are structured hierarchically (root -> list/detail).
- TypeScript is your helper. By using
as const, your keys remain literal types, ensuring you don’t accidentally pass a string where an array is expected. - Centralize for mutation. Use your factories inside mutation success handlers to ensure that your UI always invalidates the correct slices of the cache, keeping your data fresh and consistent.
Remember: Scaling Svelte Query is not about how many queries you can write, but about how well you can manage the cache. Key factories and queryOptions provide the structure needed to prevent your application from becoming a tangled web of stale data. When you treat your query keys as a first-class schema rather than arbitrary strings, you unlock the full power of client-side state management.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!