Svelte Query 04 ⚡ Reactive Query Keys & Dependent Queries — Integrating $state/$derived into query keys and controlling execution with enabled
In Svelte 5, the true power of Svelte Query is unlocked when you treat query keys not as static strings, but as reactive expressions. By injecting $state or $derived values directly into your queryKey arrays, you effectively turn your data-fetching logic into a reactive state machine. When the underlying state changes, the key changes, and Svelte Query automatically handles the teardown of the old request and the initiation of the new one.
This chapter explores how to build sophisticated data chains, specifically focusing on “dependent queries.” Often, you need to fetch data based on the results of a previous operation or a specific application state. We will examine how to use the enabled option to create a “gatekeeper” mechanism, ensuring queries only execute when their dependencies are fully satisfied, preventing malformed network requests and redundant API traffic.
Key point: Reactive query keys act as dependency trackers that trigger automatic re-fetches; dependent queries rely on the enabled option to pause execution until specific state or previous query data is available, forming a clean, sequential data pipeline.
Why exists
- The Request Synchronization problem. APIs often require IDs or parameters that arrive asynchronously, making static fetching insufficient.
- The Dependency Chain problem. UI components often depend on a user being logged in or a specific resource existing before a second call can be made.
- The “400 Bad Request” problem. Sending
nullorundefinedas a query parameter frequently triggers API errors; theenabledflag solves this by keeping the query idle. - The State Synchronization problem. Keeping the cache perfectly aligned with the user’s current search/filter state requires the cache key to mutate whenever the UI state mutates.
- The Performance/Efficiency problem. By tying the
enabledflag to reactive state, you avoid firing queries for data the user hasn’t explicitly navigated to or satisfied the conditions for.
a. Dynamic keys with $state and $derived
A query key is the heartbeat of Svelte Query’s caching mechanism. In Svelte 5, you don’t need manual watch or effect blocks to trigger updates. By referencing a $state or $derived value inside the getter function passed to createQuery, you create a direct reactive link between your UI and your cache.
let category = $state('all');
let page = $state(1);
// This query automatically restarts when category or page changes
const itemsQuery = createQuery(() => ({
queryKey: ['items', category, page],
queryFn: () => fetchItems(category, page),
}));
Because the queryKey is part of the reactive getter, Svelte Query sees a new array reference whenever category or page changes. It marks the old query as stale, triggers the new queryFn, and seamlessly swaps the data in your data rune.
b. Dependent Queries: Chaining logic
Dependent queries occur when a query’s input depends on the data of a previous query. For example, you might fetch a userId from an auth service, and only then proceed to fetch the userProfile. You handle this by tying the enabled property of the second query to the completion of the first.
const authQuery = createQuery(() => ({
queryKey: ['auth'],
queryFn: fetchAuthUser,
}));
// Only runs when authQuery.data exists
const profileQuery = createQuery(() => ({
queryKey: ['profile', authQuery.data?.id],
queryFn: () => fetchProfile(authQuery.data.id),
enabled: !!authQuery.data?.id,
}));
By setting enabled: !!authQuery.data?.id, you ensure that profileQuery stays in a pending (or disabled) state until the authentication handshake is complete. Once the data arrives, Svelte Query automatically transitions the dependent query to active.
c. Controlling execution with enabled
The enabled flag is a powerful boolean gate. Beyond dependent queries, it is useful for controlling UI-driven data loads, such as fetching search results only after a user has typed at least three characters or after a “Search” button is clicked.
let searchQuery = $state('');
const searchResults = createQuery(() => ({
queryKey: ['search', searchQuery],
queryFn: () => fetchResults(searchQuery),
// Don't fetch unless we have a meaningful query
enabled: searchQuery.length >= 3,
}));
This ensures your API isn’t spammed with empty or trivial requests. It makes your application more resilient and significantly cleaner, as you no longer need if statements inside your queryFn to check for valid input.
Complete Example Session
// ============================================
// PART 1: THE PRIMARY QUERY
// ============================================
const userQuery = createQuery(() => ({
queryKey: ['user'],
queryFn: fetchUser,
}));
// ============================================
// PART 2: THE DEPENDENT QUERY
// ============================================
const postsQuery = createQuery(() => ({
queryKey: ['posts', userQuery.data?.id],
queryFn: () => fetchPosts(userQuery.data.id),
enabled: !!userQuery.data?.id,
}));
// ============================================
// PART 3: REACTIVE FILTERS
// ============================================
let sort = $state('asc');
const sortedPosts = createQuery(() => ({
queryKey: ['posts', userQuery.data?.id, sort],
queryFn: () => fetchSortedPosts(userQuery.data.id, sort),
enabled: !!userQuery.data?.id,
}));
// ============================================
// PART 4: DERIVED DEPENDENCIES
// ============================================
let search = $state('');
let debouncedSearch = $derived(search); // Simplified
const filtered = createQuery(() => ({
queryKey: ['filtered', debouncedSearch],
queryFn: () => api.search(debouncedSearch),
enabled: debouncedSearch.length > 2
}));
// ============================================
// PART 5: CLEANUP AND RESET
// ============================================
// Svelte Query automatically handles cache
// swapping when keys change.
This sequence builds from a simple base query to complex chains using dependencies, reactive filters, and validation gates.
Quick Reference
Key Integration
| State Type | Integration | Behavior |
|---|---|---|
$state | Included in key | Triggers refetch on change |
$derived | Included in key | Reactive key update |
!!value | Used in enabled | Gates query execution |
Execution Gates
| Property | Condition | State if False |
|---|---|---|
enabled: true | Always | Active |
enabled: !!val | Val must exist | Idle / Pending |
enabled: len > 3 | Val must be long | Idle / Pending |
Cache Lifecycle
| Trigger | Result |
|---|---|
| Key change | New query entry |
| Same key | Cache hit |
enabled toggle | Run/Stop lifecycle |
Best Practices
✅ Do This:
// Use derived state for search inputs
queryKey: ['search', debouncedSearch] // ✅
// Gate queries with auth checks
enabled: !!user // ✅
// Keep dependency keys simple
queryKey: ['resource', id] // ✅
// Handle loading state for dependent queries
if (profileQuery.isLoading) return <Spinner />; // ✅
❌ Don’t Do This:
// Don't put large objects in keys
queryKey: ['user', { ...hugeObject }] // ❌
// Don't ignore dependency failures
// (check query status) // ❌
// Don't fetch before state is ready
enabled: true // causes 400 errors // ❌
// Don't trigger state updates in queryFn
queryFn: () => { loading = true; ... } // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Unnecessary fetches | Key contains unstable objects | Use object IDs (e.g., id) |
| 400 Bad Request | enabled not checking for existence | Use enabled: !!id |
| Flash of content | Missing dependent state logic | Handle isPending states |
| Syncing issues | Manual refetching instead of keys | Let key changes trigger fetches |
Real-World Examples
1. Auth-dependent profile fetch
enabled: !!user.token
2. Search filtering
queryKey: ['search', query.trim()]
3. Paginated grid
queryKey: ['items', pageNumber]
4. Conditional data fetch
enabled: !!selectedId && !isArchived
5. Dashboard widgets
queryKey: ['stats', timeframe]
6. Multi-step forms
enabled: step > 1
7. Reactive category view
queryKey: ['products', category]
8. Polling with condition
enabled: !isPaused
9. Prefetching dependent
client.prefetchQuery({ queryKey: ['details', id] })
10. Clear query after logout
client.removeQueries({ queryKey: ['user'] })
Visual
Reactive Dependency Chain
┌──────────────────────────────────────────────┐
│ $state (User ID) ──► Query Key [ 'user', id ]
│ │ │
│ [ Dependent Query ] ◄────┘ │
│ (Profile) ──► enabled: !!id │
└──────────────────────────────────────────────┘
The Enabled Gate
┌──────────────────────────────────────────────┐
│ State (val) ──► Gate (enabled) │
│ ───────┬─────── │ │
│ ▼ ▼ │
│ [ Idle State ] [ Fetching State ] │
└──────────────────────────────────────────────┘
Cache Key Mutation
┌──────────────────────────────────────────────┐
│ [ 'data', 1 ] ──► [ 'data', 2 ] │
│ │ │ │
│ (Cache Hit) (Cache Miss / Fetch) │
└──────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Reactive tracking | Key array reactivity |
| Dependency control | enabled flag |
| State integration | $state / $derived |
| Primary use | Dependent data flows |
| Cache strategy | Key-driven replacement |
Key takeaways:
- Reactive keys are automatic. Including
$stateor$derivedin aqueryKeyarray creates an observable link; changing the value automatically refetches the data. - Dependent queries use
enabled. Chaining queries is achieved by using the result of a previous query in the key of the next and settingenabled: !!data. - Validation is built-in. Use the
enabledoption as a gatekeeper to protect your API from invalid parameters. - Cache keys identify uniqueness. If a state value changes, the key changes, and Svelte Query treats it as a unique request, ensuring no state collisions.
- Declarative vs. Imperative. Stop manually calling fetch in lifecycle hooks; describe the dependencies in the key, and let the library manage the timing.
Remember: By weaving your application state directly into your query keys, you stop managing network requests and start managing dependencies. The combination of dynamic keys and the enabled flag allows you to construct complex, asynchronous data pipelines that are perfectly synchronized with your UI, ensuring that data is always fresh, valid, and available exactly when it’s needed.
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!