| | |

Svelte Query 03 ⚡ createQuery & Svelte 5 Runes — Writing query keys, query functions, and passing reactive getter options

⏱️ Estimated read: 8 min | |

In Svelte 5, reactivity is fundamentally redefined by runes. Svelte Query adapts to this architecture through the createQuery primitive, which replaces the more traditional hook-style patterns with a reactive approach that tracks dependencies automatically. The most critical aspect of this integration is the use of the “getter option” pattern, where you pass a function that returns an options object rather than the object itself. This function acts as a reactive source; when the state accessed inside that getter changes, Svelte Query automatically re-evaluates the query.

This chapter explores how to structure your queries using this reactive paradigm. We will examine the lifecycle of a queryKey, how to ensure it remains stable, and how to define queryFn implementations that respond dynamically to changes in your local rune-based state. By mastering these patterns, you eliminate the need for manual onMount effects or manual refetching logic, allowing your data layer to stay in perfect sync with your UI state.

Key point: The () => ({ ... }) pattern is the foundation of Svelte 5 reactivity in Svelte Query; by passing a getter function, you provide Svelte Query with a stable dependency that it can track, ensuring the query refetches automatically when any rune accessed within that function changes.


Why exists

  • The Reactivity Sync problem. Traditional hooks often require manual dependency arrays; the getter pattern allows the query to treat your UI state as a reactive data source.
  • The Stale Closure problem. When using standard objects as options, variables can become “captured” and stale; the getter pattern ensures the most recent values are always used.
  • The Dynamic Parameter problem. Server requests often depend on local user input (like a search filter or ID); the getter pattern allows these values to flow into the queryKey and queryFn seamlessly.
  • The enabled toggle problem. Many queries shouldn’t run until a condition is met (e.g., a user ID is present); the getter pattern allows reactive control over the enabled option.
  • The Performance/Re-render problem. Creating and destroying query instances as component variables change is expensive; Svelte Query handles the teardown and restart of the query life-cycle automatically based on the getter output.

a. The createQuery primitive and the getter pattern

The createQuery function in the Svelte 5 adapter is designed to receive a getter function. This is a deliberate design choice that aligns with Svelte’s signals. By passing () => ({ ... }), you aren’t just passing options; you are passing a reactive computation. Svelte Query monitors this function. Whenever a signal or rune inside the function is read, that query becomes dependent on that value.

// The standard reactive pattern
const userQuery = createQuery(() => ({
  queryKey: ['user', userId],
  queryFn: () => fetchUser(userId),
}));

If userId changes, the query detects that its dependency has changed and automatically triggers a re-fetch. You don’t need to manually clear the cache or call an invalidateQueries method unless you specifically need to force an update beyond the automated dependency tracking.

b. Query keys: Building reactive, stable arrays

A query key is the unique identifier for your cache. In Svelte 5, because we are using runes, we often build keys that include reactive values. The key itself must be serializable. A common mistake is to create a dynamic key that changes its shape unexpectedly. Instead, treat the key as a stable array of primitives and reactive variables.

let filters = $state({ category: 'all', limit: 10 });

const listQuery = createQuery(() => ({
  // The key updates automatically when filters change
  queryKey: ['posts', filters.category, filters.limit],
  queryFn: () => fetchPosts(filters),
}));

Svelte Query treats the array as a dependency tree. If filters.category changes, the array evaluates to a new value, Svelte Query recognizes this as a key change, and immediately initiates a request for the new key while maintaining the existing data for the old key in the cache.

c. Query functions and passing parameters

Your queryFn should be a pure function that takes the necessary data to perform the request. Because the queryFn is defined inside the getter function (or captured within it), it always has access to the current state of your variables. This makes it trivial to pass parameters to your API client.

const postsQuery = createQuery(() => ({
  queryKey: ['posts', filters.category],
  queryFn: async () => {
    // This function captures the current 'filters' rune
    const response = await api.get('/posts', { params: filters });
    return response.data;
  },
  enabled: !!filters.category // Only run when category is set
}));

The enabled option is particularly powerful here. By tying it to a boolean rune, you can stop a query from firing until, for instance, a search query is long enough or a modal is opened. The query remains in a ‘pending’ or ‘disabled’ state until the condition in the getter becomes true.


Complete Example Session

// ============================================
// PART 1: DEFINING STATE
// ============================================
let userId = $state(1);

// ============================================
// PART 2: BASIC REACTIVE QUERY
// ============================================
const userQuery = createQuery(() => ({
  queryKey: ['user', userId],
  queryFn: () => fetchUser(userId),
}));

// ============================================
// PART 3: MANAGING MULTIPLE DEPENDENCIES
// ============================================
let page = $state(1);
let search = $state('');

const searchResult = createQuery(() => ({
  queryKey: ['search', search, page],
  queryFn: () => api.search(search, page),
}));

// ============================================
// PART 4: THE ENABLED PATTERN
// ============================================
const conditionalQuery = createQuery(() => ({
  queryKey: ['details', userId],
  queryFn: () => fetchDetails(userId),
  enabled: userId > 0,
}));

// ============================================
// PART 5: ERROR HANDLING & LOADING
// ============================================
let status = $derived(userQuery.status);
let data = $derived(userQuery.data);

// ============================================
// PART 6: UPDATING STATE
// ============================================
function nextUser() { userId++; }

// ============================================
// PART 7: QUERY CLIENT INTERACTION
// ============================================
import { useQueryClient } from '@tanstack/svelte-query';
const client = useQueryClient();
function invalidate() { client.invalidateQueries({ queryKey: ['user'] }); }

// ============================================
// PART 8: INITIAL DATA
// ============================================
const fastQuery = createQuery(() => ({
  queryKey: ['fast'],
  queryFn: fetchFast,
  initialData: { id: 0, name: 'Guest' },
}));

// ============================================
// PART 9: REFETCHING STRATEGY
// ============================================
const poller = createQuery(() => ({
  queryKey: ['poll'],
  queryFn: fetchPoll,
  refetchInterval: 5000,
}));

// ============================================
// PART 10: COMPLEX DATA TRANSFORMATION
// ============================================
const processed = $derived(userQuery.data?.map(i => i.toUpperCase()));

This sequence covers the evolution of a query from a simple state-bound fetch to a complex, conditionally enabled polling operation.


Quick Reference

Getter Option Structure

PartRole
() => ({ ... })Reactive source
queryKeyCache identifier (Array)
queryFnData fetching logic
enabledExecution control (Boolean)

Reactive Features

FeatureSvelte 5 Implementation
Dependency trackingAutomatic via getter
State accessRunes ($state, $derived)
CleanupAutomatic on getter change

Common Query Keys

Key TypeStructure
Resource list['resource']
Resource item['resource', id]
Filtered list['resource', { filter }]
Paginated list['resource', page]

Best Practices

✅ Do This:

// Use arrow functions for the getter
createQuery(() => ({ ... }))                                  // ✅

// Keep keys serializable
queryKey: ['post', id]                                         // ✅

// Derive state from query data
let items = $derived(query.data ?? [])                         // ✅

// Always check for enabled condition
enabled: !!id                                                  // ✅

❌ Don’t Do This:

// Don't pass an object directly
createQuery({ queryKey: [...] }) // Not reactive!            // ❌

// Don't use non-serializable keys
queryKey: ['user', () => console.log]                          // ❌

// Don't mutate state inside queryFn
queryFn: () => { data = 1; return data; }                      // ❌

// Ignore the enabled property for optional data
// (causes useless fetches)                                     // ❌

Common Pitfalls

PitfallWhy It HappensFix
No ReactivityPassing object instead of getterUse () => ({...})
Infinite LoopUpdating state in queryFnKeep queryFn pure
Key BloatUnstable object referencesUse plain primitives
Missing DataQuery isn’t enabledCheck logic for enabled

Real-World Examples

1. Search with debounce logic

createQuery(() => ({ queryKey: ['search', debouncedVal], queryFn: () => fetch(debouncedVal) }))

2. User Profile

createQuery(() => ({ queryKey: ['user', userId], queryFn: () => fetchUser(userId) }))

3. Paginated Data

createQuery(() => ({ queryKey: ['logs', page], queryFn: () => fetchLogs(page) }))

4. Conditional Auth

createQuery(() => ({ queryKey: ['me'], queryFn: fetchMe, enabled: loggedIn }))

5. Polling Intervals

createQuery(() => ({ queryKey: ['stats'], queryFn: getStats, refetchInterval: 1000 }))

6. Stale time configuration

createQuery(() => ({ queryKey: ['key'], queryFn: fn, staleTime: 60000 }))

7. Retrying requests

createQuery(() => ({ queryKey: ['data'], queryFn: fn, retry: 3 }))

8. Select transformation

createQuery(() => ({ queryKey: ['data'], queryFn: fn, select: data => data.items }))

9. Placeholder data

createQuery(() => ({ queryKey: ['id'], queryFn: fn, placeholderData: prev => prev }))

10. Manual invalidation trigger

const query = createQuery(() => ({ ... })); // Query instance

Visual

The Reactive Getter Loop

┌──────────────────────────────────────────────┐
│  RUNE (state)  ──► GETTER FUNCTION           │
│                         │                    │
│                  TRIGGER RE-EVALUATION       │
│                         │                    │
│  NEW OPTIONS ◄──────────┘                    │
│                         │                    │
│  QUERY RE-FETCH ◄───────┘                    │
└──────────────────────────────────────────────┘

Query Key Tree

┌──────────────────────────────────────────────┐
│  ['posts', category, page]                   │
│      │         │        │                    │
│      │         └────────┼──► [ page 2 ]      │
│      └──────────────────┼──► [ 'tech' ]      │
│                         │                    │
│  NEW KEY = ['posts', 'tech', 2]              │
└──────────────────────────────────────────────┘

Enabled Flag Control

┌──────────────────────────────────────────────┐
│  ID > 0 ──────► [ QUERY ACTIVE ]             │
│  ID == 0 ─────► [ QUERY DISABLED ]           │
│                                              │
│  Allows for clean "empty" states before      │
│  valid input exists.                         │
└──────────────────────────────────────────────┘

Summary

ItemValue
PrimitivecreateQuery
Input patternGetter function () => ({...})
Key stabilityUse serializable primitives
Execution flowReactive dependency tracking
ConditionalsUse enabled property

Key takeaways:

  • Getter functions are reactive. By using () => ({ ... }), you inform Svelte Query that the query depends on the values accessed within the function, enabling automatic re-fetching.
  • Keys must be stable. Always structure keys as arrays of serializable data (strings, numbers, simple objects) to avoid unnecessary re-fetches.
  • enabled is your friend. Avoid fetching data when parameters are incomplete; use the enabled option to conditionally trigger queries based on component state.
  • Keep query functions pure. Do not attempt to modify external state inside the queryFn; return data only.
  • Leverage Svelte 5 runes. The tight coupling between $state and the query options getter is the primary engine for Svelte 5 data management.

Remember: createQuery transforms your data fetching into a declarative stream. By thinking in terms of reactive getters, you shift from “imperatively fetching on mount” to “describing the state requirements of your UI.” If the UI state changes, the requirement definition changes via the getter, and Svelte Query seamlessly updates the cache and the resulting data.

Was this helpful?


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!