| | |

Vue Query 04 ⚡ Reactive Query Keys & Options — Using ref/computed inside query keys, enabled flags, and Vue 3 reactivity tracking

⏱️ Estimated read: 11 min | |

Vue Query is designed to feel like a native extension of the Vue 3 reactivity system. While other state management libraries require manual “useEffect” style hooks or watchers to trigger data refreshes, Vue Query leverages the declarative nature of ref and computed properties. By including reactive variables directly in the Query Key, you create an automatic link: when your local state changes, your server state synchronizes. This eliminates the need for imperative “loadData” functions scattered across your components, replacing them with a single, self-updating source of truth.

The orchestration of these reactive updates is controlled through the options object passed to useQuery. The most critical of these is the enabled flag, which serves as the “gatekeeper” for your requests. In many real-world scenarios, you cannot fetch data immediately—perhaps you are waiting for a user ID to be available, or you only want to search once a string reaches a certain length. By passing a reactive boolean to enabled, you can precisely control when the network request should fire, preventing unnecessary 404s or malformed API calls.

This chapter explores the deep integration between Vue’s reactivity and TanStack Query. We will examine how query keys act as dependency arrays, how to handle dependent queries where one request relies on the result of another, and how Vue Query optimizes performance through “reactive tracking.” By mastering these patterns, you move from simple data fetching to building highly interactive, state-driven interfaces that feel instantaneous to the user.

Key point: Query Keys in Vue Query act as reactive dependencies; including a ref or computed in a key array ensures that the query automatically refetches whenever that value changes, provided the enabled option is true.


Why exists

The Manual Watcher problem.
In standard Vue, if you have a search bar, you must write a watch function to monitor the input and trigger a fetch. This separates the “trigger” from the “data,” making the code harder to follow. Vue Query exists to unify this; by putting the search term in the Query Key, the “trigger” becomes a natural part of the data definition.

The Null-Pointer/Dependent Query problem.
Often, you need to fetch “Comments” but you don’t have a “Post ID” yet because the post is still loading. Making a request with an undefined ID results in server errors. The enabled option exists to pause the query until all required dependencies are valid, allowing for a clean “waterfall” of data fetching without manual checks.

The Race Condition problem.
If a user types quickly in a search bar, multiple requests might be sent. If the first request takes 2 seconds and the second takes 0.5 seconds, the UI might display the old results last. Vue Query’s reactive keys handle this internally by automatically canceling previous out-of-date requests when a key changes, ensuring the UI stays in sync with the latest state.

The Conditional Loading problem.
Sometimes you want to define a query but not execute it immediately (e.g., a “Load More” button or a toggleable sidebar). Vue Query provides the enabled flag so you can declare the query’s logic once at the top of your component and trigger the actual execution based on user interaction or logic.

The Optimization problem.
Re-rendering components is expensive. If a query returns a large object but you only use the data property, you don’t want the component to re-render when the isFetching flag changes. Vue Query exists to track which reactive properties of the query result are actually used in your template, minimizing unnecessary Vue re-renders.


a. Reactive Query Keys: refs and computed

In Vue Query, the queryKey is watched by the library. If any part of the array is reactive (a ref, reactive, or computed), Vue Query automatically creates a dependency. When that value changes, the query is marked as “stale” and a refetch is triggered if the component is still mounted.

<script setup>
import { ref, computed } from 'vue'
import { useQuery } from '@tanstack/vue-query'

const category = ref('electronics')
const page = ref(1)

// This query re-runs if category OR page changes
const { data } = useQuery({
  queryKey: ['products', category, page],
  queryFn: () => fetchProducts(category.value, page.value)
})
</script>

It is often cleaner to use a computed property for complex keys, especially if they require transformations or filtering. Vue Query will treat the computed property as a single dependency within the key array.

const queryFilters = computed(() => ({
  cat: category.value,
  p: page.value,
  search: searchTerm.value.trim().toLowerCase()
}))

const { data } = useQuery({
  queryKey: ['products', queryFilters], // Automatically unwraps computed
  queryFn: () => api.getProducts(queryFilters.value)
})

Because Vue Query performs a “deep equality” check on objects inside keys, the query will not refetch if the computed object looks identical to its previous version, even if the object reference itself is new. This prevents redundant network calls.


b. The enabled Flag and Dependent Queries

The enabled option accepts a boolean or a reactive getter. If it is false, the query will not run, even if the query key changes. This is the primary mechanism for “Dependent Queries”—queries that wait for data from a previous request.

<script setup>
// 1. Get the user
const { data: user } = useQuery({
  queryKey: ['user', email],
  queryFn: () => fetchUserByEmail(email.value)
})

const userId = computed(() => user.value?.id)

// 2. Get the user's projects (Only when userId exists)
const { data: projects } = useQuery({
  queryKey: ['projects', userId],
  queryFn: () => fetchProjects(userId.value),
  // The query is "Disabled" until userId has a value
  enabled: computed(() => !!userId.value)
})
</script>

When enabled is false, the query enters a status: 'pending' and fetchStatus: 'idle' state. As soon as the condition becomes true, Vue Query initiates the request.

This is also useful for “Lazy Queries.” You can set enabled to a ref called isExpanded. The data for a sidebar or modal will only be fetched the moment the user actually opens that UI element, saving bandwidth for users who never use those features.


c. Reactivity Tracking and Performance

One of the most sophisticated features of the Vue 3 integration is “Tracked Queries.” When you destructure the result of useQuery, the library keeps track of which properties you are actually using in your component.

const { data, isLoading } = useQuery({ queryKey: ['x'], queryFn: fetchX })

In the example above, Vue Query knows you are using data and isLoading. If a background refetch happens and isFetching changes from true to false, but the data remains the same, your component will not re-render. This is because you didn’t destructure or use isFetching.

This optimization is built-in. It allows you to use complex queries that return many metadata flags without worrying about the performance hit of constant re-rendering during background synchronization.

Furthermore, if you pass a reactive object as an option (like staleTime or retry), Vue Query will respect the changes to those options in real-time. You could, for example, have a “Real-time Mode” toggle that changes refetchInterval from 0 to 5000 dynamically.


Complete Example Session

// ============================================
// PART 1: SEARCH STATE
// ============================================
const search = ref('')
const debouncedSearch = refDebounced(search, 500) // Using @vueuse/core

// ============================================
// PART 2: DEPENDENT QUERY DATA
// ============================================
const { data: user } = useQuery({
  queryKey: ['me'],
  queryFn: fetchMe
})

// ============================================
// PART 3: THE MAIN REACTIVE QUERY
// ============================================
const { data: results, isFetching } = useQuery({
  // Key depends on user ID and search term
  queryKey: ['search', computed(() => user.value?.id), debouncedSearch],

  queryFn: async () => {
    return api.search(user.value.id, debouncedSearch.value)
  },

  // PART 4: THE ENABLED GATEKEEPER
  // Don't search if not logged in OR search is too short
  enabled: computed(() => !!user.value?.id && debouncedSearch.value.length > 2),

  // PART 5: DYNAMIC CONFIG
  // Only poll if search is active
  refetchInterval: computed(() => debouncedSearch.value ? 10000 : 0)
})

// ============================================
// PART 6: DERIVED COMPUTED FROM QUERY
// ============================================
const hasResults = computed(() => (results.value?.length ?? 0) > 0)

// ============================================
// PART 7: LOGGING DEPENDENCY UPDATES
// ============================================
// If search.value changes, debouncedSearch follows after 500ms, 
// then QueryKey changes, then refetch occurs automatically.

// ============================================
// PART 8: LAZY FETCHING PATTERN
// ============================================
const showDetails = ref(false)
const { data: details } = useQuery({
  queryKey: ['details', results],
  queryFn: fetchDetails,
  enabled: showDetails // Only runs when user clicks 'Expand'
})

// ============================================
// PART 9: ACCESSING CACHE STATUS
// ============================================
// results.status will be 'pending' while search is enabled: false

// ============================================
// PART 10: AUTOMATIC CLEANUP
// ============================================
// When component unmounts, Vue Query stops watching these refs.

The session above illustrates how multiple reactive streams (user status, debounced search input, and UI toggles) converge into a single query definition that manages its own execution lifecycle.


Quick Reference

Key Reactive Types in queryKey

TypeExampleBehavior
ref['id', userId]Triggers refetch on .value change
computed['list', filters]Triggers if computed result changes
reactive['config', state]Triggers on any property change
Static['logs']Only fetches on mount or invalidation

Common useQuery Options

OptionPurposeAccepts Reactive?
enabledPauses/Starts queryYes (Boolean/Computed)
staleTimeHow long data is freshYes (Number)
refetchIntervalPolling frequencyYes (Number/False)
retryFailure behaviorYes

Query States when enabled: false

PropertyValueDescription
status'pending'The query is waiting to run
fetchStatus'idle'No network call is active
isLoadingtrueTrue because data is missing
isFetchingfalseFalse because request is paused

Best Practices

✅ Do This:

// Use computed for 'enabled' to keep logic clean
enabled: computed(() => !!id.value && isReady.value)           // ✅

// Always include reactive variables in the queryKey
queryKey: ['user', userId] // userId is a ref                 // ✅

// Use refs for dynamic pagination or filtering
const page = ref(1); queryKey: ['items', page]                // ✅

// Use lazy loading for expensive queries
const isVisible = ref(false); enabled: isVisible               // ✅

❌ Don’t Do This:

// Don't manually watch a ref to call refetch()
watch(id, () => refetch()) // redundant; use reactive keys     // ❌

// Don't pass raw values to queryFn if they are in the key
// (useQuery passes the key context to the function instead)   // ❌

// Don't use a constant true for enabled if dependencies exist
enabled: !!id.value // Use computed to keep it reactive        // ❌

// Don't destructure the result if you want to avoid re-renders
// (though Vue Query 5+ handles this well automatically)       // ❌

Common Pitfalls

PitfallWhy It HappensFix
No refetch on changeVariable was passed as .value in the keyPass the ref itself or a computed
Query runs with nullenabled was not used to guard the queryAdd enabled: computed(() => !!val)
Infinite LoopqueryFn changes the ref used in queryKeyQuery functions must be side-effect free
Data is staleKey didn’t change but data is oldAdd a unique ID or timestamp to the key
enabled not reactivePassed a plain boolean instead of a RefWrap logic in computed() or pass a Ref<boolean>
Tracking not workingUsing standard variables instead of refEnsure inputs are Vue reactive objects

Real-World Examples

1. Search as you type

const { data } = useQuery({ queryKey: ['search', query], queryFn: () => search(query.value) });

2. Dependent User Settings

const { data } = useQuery({ queryKey: ['set'], queryFn: getSet, enabled: computed(() => !!user.value) });

3. Modal Data on Open

const { data } = useQuery({ queryKey: ['m'], queryFn: getM, enabled: isModalOpen });

4. Pagination

const page = ref(1); const { data } = useQuery({ queryKey: ['p', page], queryFn: () => getP(page.value) });

5. Poll only when tab is active

refetchInterval: computed(() => isTabActive.value ? 5000 : 0)

6. Admin-only Queries

enabled: computed(() => user.value?.role === 'admin')

7. Multi-filter Dashboard

const filters = reactive({ color: 'red', size: 'M' });
const { data } = useQuery({ queryKey: ['items', filters], queryFn: () => getItems(filters) });

8. Waiting for Route Params

const route = useRoute();
const { data } = useQuery({ queryKey: ['item', computed(() => route.params.id)], ... });

9. Dynamic Stale Time

staleTime: computed(() => isDev ? 0 : 60000)

10. Re-fetching on Locale Change

const { locale } = useI18n();
const { data } = useQuery({ queryKey: ['content', locale], queryFn: () => getContent(locale.value) });

Visual

The Reactivity Loop

┌──────────────────────────────────────────────────────────┐
│  USER INTERACTION                                        │
│  (Change ref value: page.value = 2)                      │
└─────────────┬────────────────────────────────────────────┘
              │ 1. Triggers Watcher
              ▼
┌──────────────────────────────────────────────────────────┐
│  VUE QUERY ENGINE                                        │
│  Detects Query Key ['items', 2] is different from        │
│  previous ['items', 1]                                   │
└─────────────┬────────────────────────────────────────────┘
              │ 2. Initiates Network Call
              ▼
┌──────────────────────────────────────────────────────────┐
│  SERVER RESPONSE ──► UPDATES CACHE ──► UPDATES UI        │
└──────────────────────────────────────────────────────────┘

Dependent Query Waterfall

┌──────────────────┐      ┌───────────────────────────────┐
│  QUERY A (User)  │─────►│  RESULT: { id: 42 }           │
└──────────────────┘      └─────────────┬─────────────────┘
                                        │
                          ┌─────────────▼─────────────────┐
                          │  COMPUTED enabled: !!user.id  │
                          │  (Flips from false to true)   │
                          └─────────────┬─────────────────┘
                                        │
                          ┌─────────────▼─────────────────┐
                          │  QUERY B (Projects)           │
                          │  queryKey: ['projects', 42]   │
                          └───────────────────────────────┘

Reactivity Tracking Optimization

┌──────────────────────────┐      ┌──────────────────────────┐
│   useQuery Result        │      │   Component View         │
├──────────────────────────┤      ├──────────────────────────┤
│ data        (Used)       │─────►│ Renders Data             │
│ isPending   (Used)       │─────►│ Renders Spinner          │
│ isFetching  (NOT Used)   │──X──►│ (Ignore updates)         │
│ error       (NOT Used)   │──X──►│ (Ignore updates)         │
└──────────────────────────┘      └──────────────────────────┘
 (Only 'Used' properties trigger a Vue component re-render)

Summary

ItemValue
Dependency ToolQuery Key (Array)
Trigger MechanismVue Reactivity (Ref/Computed)
Conditional Triggerenabled option
Performance ToolAutomatic property tracking
Equality CheckDeep object comparison
Logic PatternDeclarative synchronization
Status if disabledpending / idle

Key takeaways:

  • Query Keys are living dependencies. By including reactive Vue objects in the key array, you tell Vue Query exactly what pieces of local state should trigger a server-side refresh .
  • The enabled option is a powerful gatekeeper. Use it to prevent invalid requests, create dependent “waterfall” queries, or implement lazy-loading UI patterns .
  • Vue 3 deep tracking reduces re-renders. Vue Query is smart enough to only update your component if a property you are actually using in your template or script changes .
  • Computed properties simplify complex keys. If a key depends on multiple filters or requires data cleaning, wrap the logic in a computed and pass that to the key array .
  • Wait for your data. Use enabled: computed(() => !!dependency.value) to ensure your query function always has the valid arguments it needs before it executes .
  • Reactive options enable dynamic behavior. Options like refetchInterval can be reactive, allowing your app to switch between “live” and “static” modes without unmounting queries .

Remember: Don’t tell Vue Query when to fetch; tell it what the data depends on. Use reactive keys to link your UI state to your cache and use the enabled flag to define the conditions under which that link is active. This creates a self-managing data layer that scales effortlessly with your application’s complexity.

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!