| | |

Vue Query 15 ⚡ Cheatsheet

⏱️ Estimated read: 3 min | |

Install & Setup

npm install @tanstack/vue-query
// main.ts
import { VueQueryPlugin, QueryClient } from '@tanstack/vue-query'

const queryClient = new QueryClient({
  defaultOptions: { queries: { staleTime: 30_000, retry: 2 } },
})

app.use(VueQueryPlugin, { queryClient })

useQuery

import { useQuery } from '@tanstack/vue-query'

const { data, isPending, isFetching, isError, error, refetch } = useQuery({
  queryKey: ['todos'],                 // unique cache id (always an array)
  queryFn: () => fetch('/api/todos').then(r => r.json()),
  enabled: true,                        // pause execution when false
  staleTime: 0,                         // ms before data is "old"
  gcTime: 300_000,                      // ms to keep unused data in memory
})
ReturnTypeMeaning
dataRef<T>The cached/ fetched data
isPendingbooleanNo data yet, first fetch
isFetchingbooleanAny request in flight
isErrorbooleanQuery failed
errorRef<Error>The error object
refetchFunctionManual refetch

Dynamic & Dependent Keys

const id = ref(1)

// key changes -> auto refetch
const { data: user } = useQuery({
  queryKey: ['user', id],
  queryFn: () => fetchUser(id.value),
})

// dependent query: wait for first
const { data: posts } = useQuery({
  queryKey: ['posts', user],
  queryFn: () => fetchPosts(user.value.id),
  enabled: computed(() => !!user.value),
})

useMutation

import { useMutation, useQueryClient } from '@tanstack/vue-query'

const qc = useQueryClient()

const { mutate, isPending } = useMutation({
  mutationFn: (todo) => postTodo(todo),
  onSuccess: () => qc.invalidateQueries({ queryKey: ['todos'] }),
  onError: (err) => console.error(err),
})

mutate({ text: 'New todo' })   // trigger manually
HookFires
onMutateBefore mutationFn (snapshot for rollback)
onSuccessAfter success (invalidate here)
onErrorOn failure (rollback here)
onSettledAlways, after success or error

Optimistic Update

const { mutate } = useMutation({
  mutationFn: updateTodo,
  onMutate: async (newTodo) => {
    await qc.cancelQueries({ queryKey: ['todos'] })          // stop overwrite
    const previous = qc.getQueryData(['todos'])              // snapshot
    qc.setQueryData(['todos'], (old) => /* apply new */ old)
    return { previous }                                      // context
  },
  onError: (err, vars, context) => {
    qc.setQueryData(['todos'], context.previous)            // rollback
  },
  onSettled: () => qc.invalidateQueries({ queryKey: ['todos'] }),
})

queryClient Methods

qc.invalidateQueries({ queryKey: ['todos'] })   // mark stale + refetch
qc.setQueryData(['todos'], newData)             // write cache manually
qc.getQueryData(['todos'])                       // read cache (sync)
qc.prefetchQuery({ queryKey, queryFn })         // load ahead of time
qc.cancelQueries({ queryKey })                  // abort in-flight
qc.removeQueries({ queryKey })                  // delete from cache

select (transform)

const { data: names } = useQuery({
  queryKey: ['users'],
  queryFn: fetchUsers,
  select: (users) => users.map(u => u.name),   // memoized, lean re-renders
})

Retry & Network

retry: (count, err) => err.status !== 404 && count < 3   // skip 4xx
retryDelay: (attempt) => Math.min(1000 * 2 ** attempt, 30_000)
networkMode: 'online'   // 'online' | 'always' | 'offlineFirst'

SSR (Nuxt / dehydrate)

import { dehydrate, hydrate } from '@tanstack/vue-query'

// server
await qc.prefetchQuery({ queryKey, queryFn })
const state = dehydrate(qc)          // serialize into HTML

// client
hydrate(qc, state)                  // restore before mount

Testing (Vitest)

import { mount } from '@vue/test-utils'
import { VueQueryPlugin, QueryClient } from '@tanstack/vue-query'

const client = new QueryClient({
  defaultOptions: { queries: { retry: false } },  // fail fast
})

mount(Comp, {
  global: { plugins: [[VueQueryPlugin, { queryClient: client }]] },
})

await flushPromises()   // wait for query to settle before asserting

Key Options Reference

OptionDefaultPurpose
staleTime0Freshness window
gcTime5 minUnused cache lifetime
retry3Retry attempts
enabledtrueToggle execution
refetchOnWindowFocustrueRefetch on tab focus
placeholderData-Show while loading (keepPreviousData)

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!