IDE-Tools · Foto: Homedust, CC BY 2.0
Tanstack Query
Zuletzt aktualisiert:
Typ
Regel
Lizenz
CC0 1.0
Anwendungsfeld
Cursor Rules
Voraussetzungen
Keine besonderen — direkt loslegen.
Fertige Cursor-Regel für idiomatischen TanStack-Query-Code – einfach in .cursor/rules ablegen.
Original-Beschreibung der Autoren: TanStack Query v5 (React Query) patterns including queryOptions helper, query key factories, mutations, optimistic updates, infinite queries, Suspense mode, and prefetching
Die Regel
---
description: "TanStack Query v5 (React Query) patterns including queryOptions helper, query key factories, mutations, optimistic updates, infinite queries, Suspense mode, and prefetching"
globs: ["src/**/*.tsx", "src/**/*.ts", "src/queries/**/*"]
alwaysApply: false
---
You are an expert in TanStack Query v5 (React Query), TypeScript, and async state management.
## Core Principles
- TanStack Query manages server state — NOT a general client state manager
- Every query needs a stable, serializable query key that uniquely describes the data
- Mutations handle writes; queries handle reads — never blur this boundary
- Use `queryOptions()` helper (v5) for reusable, co-located query definitions
- v5 breaking change: `useQuery` only accepts options object form — no positional args
## QueryClient Setup
```tsx
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 1000 * 60,
retry: (count, error: any) => error?.status !== 404 && count < 2,
},
},
})
Query Key Factory Pattern
export const postKeys = {
all: ['posts'] as const,
lists: () => [...postKeys.all, 'list'] as const,
list: (filters?: PostFilters) => [...postKeys.lists(), filters] as const,
details: () => [...postKeys.all, 'detail'] as const,
detail: (id: string) => [...postKeys.details(), id] as const,
}
queryOptions Helper (v5)
export const postQueryOptions = (id: string) =>
queryOptions({
queryKey: postKeys.detail(id),
queryFn: () => fetchPost(id),
staleTime: 1000 * 60 * 5,
})
// In component
const { data } = useQuery(postQueryOptions(postId))
// In router loader
loader: ({ params, context: { queryClient } }) =>
queryClient.ensureQueryData(postQueryOptions(params.postId))
Mutations
const { mutate, isPending } = useMutation({
mutationFn: (input: CreatePostInput) => createPost(input),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: postKeys.lists() })
},
onError: (error) => toast.error(error.message),
})
Optimistic Updates
const mutation = useMutation({
mutationFn: updatePost,
onMutate: async (updated) => {
await queryClient.cancelQueries({ queryKey: postKeys.detail(updated.id) })
const previous = queryClient.getQueryData(postKeys.detail(updated.id))
queryClient.setQueryData(postKeys.detail(updated.id), updated)
return { previous }
},
onError: (_, updated, ctx) => {
queryClient.setQueryData(postKeys.detail(updated.id), ctx?.previous)
},
onSettled: (_, __, updated) => {
queryClient.invalidateQueries({ queryKey: postKeys.detail(updated.id) })
},
})
Infinite Queries
const { data, fetchNextPage, hasNextPage } = useInfiniteQuery({
queryKey: postKeys.lists(),
queryFn: ({ pageParam }) => fetchPosts({ cursor: pageParam }),
initialPageParam: undefined as string | undefined,
getNextPageParam: (lastPage) => lastPage.nextCursor,
})
const allPosts = data?.pages.flatMap((p) => p.items) ?? []
Suspense Mode (v5)
// useSuspenseQuery — no isLoading needed, Suspense handles it
const { data } = useSuspenseQuery(postQueryOptions(postId))
// Wrap with <Suspense fallback={<Skeleton />}> + <ErrorBoundary>
Key Rules
- Always define
queryOptionsoutside components — never inline inuseQuery() - Never use
useEffectto fetch data — use loaders oruseQuery - Use
placeholderData: keepPreviousDatafor pagination to avoid layout shifts - Instantiate
QueryClientonce at app root — never inside a component
## So nutzt du sie
Die Regel kopieren (Button oben) oder als Datei herunterladen und im Projekt unter `.cursor/rules/` ablegen — Cursor lädt sie beim nächsten Start automatisch. Ältere Cursor-Versionen lesen alternativ eine einzelne `.cursorrules`-Datei im Projektstamm; dort einfach den Regel-Text ohne den Kopfblock zwischen den `---`-Zeilen einfügen.
Der Regel-Text ist englisch — Cursor versteht ihn unabhängig von der Sprache, in der Sie mit dem Editor chatten.
## Im Detail
Diese Regel bündelt gängige Best Practices für TanStack Query (vormals React Query): saubere Trennung von Query-Keys, sinnvolle staleTime/cacheTime-Einstellungen, Query-Factories statt verstreuter Inline-Keys und korrekter Umgang mit Mutations inklusive Invalidierung. Damit verhindert sie typische KI-Fehler wie manuelles Re-Fetching per useEffect oder das Ignorieren des eingebauten Caching-Mechanismus. Wertvoll für Teams, die TanStack Query bereits im Projekt einsetzen und wollen, dass generierter Code sich an etablierte Datenabfrage-Muster hält statt an klassisches useState/useEffect-Fetching zurückzufallen. Kein Ersatz für die offizielle Doku, aber eine gute Leitplanke im Alltag.
## Praxis-Tipp
Kombinieren Sie sie mit einem Prompt wie „erstelle einen Custom Hook für /api/users mit useQuery“, damit die KI Query-Keys und Invalidierungslogik automatisch nach Projektkonvention erzeugt.
## Lizenz & Quelle
- **Lizenz:** CC0 1.0
- **Quelle:** [PatrickJS/awesome-cursorrules (GitHub)](https://github.com/PatrickJS/awesome-cursorrules)
Inhalt ansehen (tanstack-query.mdc)
Lade …
Erfahrungen & Kommentare.
Funktioniert der Regel bei Ihnen? Tipps, Stolperfallen, Varianten — teilen Sie es mit der Community.
Lade Kommentare …
Passt dazu.
AI Agent Specialist
Cursor-Regel für diszipliniertes, klar abgegrenztes Agenten-Verhalten statt unstrukturierter KI-Antworten.
Alpha Skills Quant Factor Research
Cursor-Regel für methodisch saubere quantitative Faktor-Recherche im Trading-Umfeld.
Android Jetpack Compose
Cursor-Regel für idiomatischen, deklarativen Android-UI-Code mit Jetpack Compose.
