agentleFS
LaoitdevOpenLaoitdevOpen/laoitdev-skills/skills/frontend/tanstack-query/SKILL.md

tanstack-query

Skill0 starsChanged 4 months agoMITView on GitHub

How to use TanStack Query v5 for data fetching, mutations, and cache management. Use this whenever creating hooks for API calls — list queries, single-item queries, create/update/delete mutations, or cache invalidation. Covers useQuery, useMutation, query key factories, staleTime defaults, and the service layer pattern.

19 other projects use a version of this.

Adopted by

Most recently taken up by

Used with

Projects with it also use tanstack-table, research and 2 more.

Other files people use alongside this one.

Files found in the same public projects as a version of this one, more often than they turn up anywhere else. Each project counts once, large collections count for less, and this file's own repository is left out.
  • JasonPaffSkill

    tanstack-table

    Build headless data tables with TanStack Table v8. Server-side pagination, filtering, sorting, and virtualization for Cloudflare Workers + D1. Prevents 12 documented errors.

    Also in 3 projects that use this

  • NVIDIASkill

    research

    Before designing a feature, research how comparable libraries solve the problem, check best practices, known pitfalls, and upstream changes. Use when starting a new feature, investigating an unfamiliar area, or the user asks to research something.

    Also in 4 projects that use this

  • SentrySkill

    review

    Fixture review skill.

    Also in 3 projects that use this

  • GoogleSkill

    code-review

    Adversarial systems, concurrency, memory-model, and architecture code review protocol. Use this skill whenever asked to review code, PRs, diffs, or branches in Filament.

    Also in 3 projects that use this

The file

We split this skill into the rules it gives an agent

5 rules. 0 are common, 2 are distinctive, and 3 are very specific to this project.

  • 0

    Common

    Most of the 18 edited versions we read keep these.

  • 2

    Distinctive

    This author's own choices. Worth a look.

  • 3

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Always define query keys as a factory object in the feature's constants file — never inline ad-hoc array keys.

    line 10
  2. Distinctive:

    Always define query keys as a factory object in the feature's constants file.

    line 22
  3. Very specific:

    After create: invalidate lists()

    line 218
  4. Very specific:

    After update: invalidate both lists() and detail(id)

    line 219
  5. Very specific:

    After delete: invalidate lists()

    line 220

“Common” is measured: kept by at least 6 in 10 of the 18 edited versions of this file we could read. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Data Fetching with TanStack Query

Core Invariants (always enforced — never violate)

  • Always define query keys as a factory object in the feature's constants file — never inline ad-hoc array keys.

Query Client Config

The global QueryClient is configured in @/core/config/query-client.config:

  • staleTime: 5 minutes — data stays fresh for 5 min before refetch
  • gcTime: 10 minutes — unused cache cleared after 10 min
  • retry: 1 — one retry on failure
  • refetchOnWindowFocus: false

Query Keys

Always define query keys as a factory object in the feature's constants file. This makes invalidation precise.

// constants/your-feature.constants.ts
import type { YourFeatureFilterParams } from '../types'

export const YOUR_FEATURE_QUERY_KEYS = {
  all: ['your-features'] as const,
  lists: () => [...YOUR_FEATURE_QUERY_KEYS.all, 'list'] as const,
  list: (params: YourFeatureFilterParams) => [...YOUR_FEATURE_QUERY_KEYS.lists(), params] as const,
  details: () => [...YOUR_FEATURE_QUERY_KEYS.all, 'detail'] as const,
  detail: (id: number) => [...YOUR_FEATURE_QUERY_KEYS.details(), id] as const,
}

List Query

// hooks/useYourFeatures.ts
import { useQuery } from '@tanstack/react-query'
import { YOUR_FEATURE_QUERY_KEYS } from '../constants'
import { yourFeatureService } from '../services'
import type { YourFeatureFilterParams } from '../types'

export function useYourFeatures(params?: YourFeatureFilterParams) {
  return useQuery({
    queryKey: YOUR_FEATURE_QUERY_KEYS.list(params || {}),
    queryFn: ({ signal }) => yourFeatureService.getAll(params, signal),
    staleTime: 5 * 60 * 1000,
  })
}

Single Item Query

// hooks/useYourFeature.ts
import { useQuery } from '@tanstack/react-query'
import { YOUR_FEATURE_QUERY_KEYS } from '../constants'
import { yourFeatureService } from '../services'

export function useYourFeature(id: number) {
  return useQuery({
    queryKey: YOUR_FEATURE_QUERY_KEYS.detail(id),
    queryFn: ({ signal }) => yourFeatureService.getById(id, signal),
    staleTime: 5 * 60 * 1000,
    enabled: !!id,
  })
}

Create Mutation

// hooks/useCreateYourFeature.ts
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { YOUR_FEATURE_QUERY_KEYS } from '../constants'
import { yourFeatureService } from '../services'
import type { YourFeatureCreateRequest } from '../types'

export function useCreateYourFeature() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: (data: YourFeatureCreateRequest) => yourFeatureService.create(data),
    onSuccess: () => {
      // Invalidate the list so it refetches
      queryClient.invalidateQueries({ queryKey: YOUR_FEATURE_QUERY_KEYS.lists() })
    },
  })
}

Update Mutation

// hooks/useUpdateYourFeature.ts
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { YOUR_FEATURE_QUERY_KEYS } from '../constants'
import { yourFeatureService } from '../services'
import type { YourFeatureUpdateRequest } from '../types'

export function useUpdateYourFeature(id: number) {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: (data: YourFeatureUpdateRequest) => yourFeatureService.update(id, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: YOUR_FEATURE_QUERY_KEYS.lists() })
      queryClient.invalidateQueries({ queryKey: YOUR_FEATURE_QUERY_KEYS.detail(id) })
    },
  })
}

Delete Mutation

// hooks/useDeleteYourFeature.ts
import { useMutation, useQueryClient } from '@tanstack/react-query'
import { YOUR_FEATURE_QUERY_KEYS } from '../constants'
import { yourFeatureService } from '../services'

export function useDeleteYourFeature() {
  const queryClient = useQueryClient()

  return useMutation({
    mutationFn: (id: number) => yourFeatureService.delete(id),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: YOUR_FEATURE_QUERY_KEYS.lists() })
    },
  })
}

Service Layer Pattern

Each feature has a service object in services/your-feature.service.ts. The service handles Axios calls; hooks handle caching.

import axiosInstance from '@/core/api/axios.config'
import { YOUR_FEATURE_ENDPOINTS } from '../constants'
import type { YourFeaturesResponse, YourFeatureDetailResponse, YourFeatureCreateRequest } from '../types'

export const yourFeatureService = {
  async getAll(params?: YourFeatureFilterParams, signal?: AbortSignal): Promise<YourFeaturesResponse> {
    const { data } = await axiosInstance.get<YourFeaturesResponse>(
      YOUR_FEATURE_ENDPOINTS.BASE, { params, signal }
    )
    return data
  },

  async getById(id: number, signal?: AbortSignal): Promise<YourFeatureDetailResponse> {
    const { data } = await axiosInstance.get<YourFeatureDetailResponse>(
      YOUR_FEATURE_ENDPOINTS.DETAIL(id), { signal }
    )
    return data
  },

  async create(payload: YourFeatureCreateRequest, signal?: AbortSignal) {
    const { data } = await axiosInstance.post(YOUR_FEATURE_ENDPOINTS.BASE, payload, { signal })
    return data
  },

  async update(id: number, payload: YourFeatureUpdateRequest, signal?: AbortSignal) {
    const { data } = await axiosInstance.put(YOUR_FEATURE_ENDPOINTS.UPDATE(id), payload, { signal })
    return data
  },

  async delete(id: number, signal?: AbortSignal) {
    const { data } = await axiosInstance.delete(YOUR_FEATURE_ENDPOINTS.DETAIL(id), { signal })
    return data
  },
}

Using Mutations in Components

const createMutation = useCreateYourFeature()

// In form onSubmit or button handler:
createMutation.mutate(formData, {
  onSuccess: () => {
    showSuccess(t('feature.createSuccess'))
    navigate({ to: '/feature' })
  },
  onError: (error) => {
    showError(translateError(error))
  },
})

// Check pending state for loading UI:
<Button disabled={createMutation.isPending}>
  {createMutation.isPending ? t('common.saving') : t('common.save')}
</Button>

Route Loader Prefetch

For detail pages, prefetch in the route loader so data is ready before the component renders:

// routes/_layout/section/feature/$featureId/index.tsx
loader: async ({ params, context }) => {
  await context.queryClient.ensureQueryData({
    queryKey: YOUR_FEATURE_QUERY_KEYS.detail(Number(params.featureId)),
    queryFn: ({ signal }) => yourFeatureService.getById(Number(params.featureId), signal),
  })
},

The component's useYourFeature(id) call then hits the cache immediately.

Cache Invalidation Strategy

  • After create: invalidate lists()
  • After update: invalidate both lists() and detail(id)
  • After delete: invalidate lists()
  • For granular invalidation, pass exact: true or specific query keys
// Invalidate all lists (any params)
queryClient.invalidateQueries({ queryKey: YOUR_FEATURE_QUERY_KEYS.lists() })

// Invalidate exact detail
queryClient.invalidateQueries({ queryKey: YOUR_FEATURE_QUERY_KEYS.detail(id) })

// Invalidate everything for this feature
queryClient.invalidateQueries({ queryKey: YOUR_FEATURE_QUERY_KEYS.all })

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.