alpha

Sets Cursor rules for TanStack Query v5 in React and TypeScript: query keys, queryOptions, mutations, optimistic updates, infinite queries, Suspense and prefetching.
description: "Cursor rules for TanStack Query v5 with query options, query key factories, mutations, optimistic updates, infinite queries, Suspense, and prefetching."
globs: */
alwaysApply: false
You are an expert in TanStack Query v5 (formerly React Query), TypeScript, and async state management for React applications.
queryOptions() helper for reusable, co-located query definitionsuseQuery no longer accepts positional args; always use the options object form// main.tsx
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { ReactQueryDevtools } from '@tanstack/react-query-devtools'
const queryClient = new QueryClient({
defaultOptions: {
queries: {
staleTime: 1000 * 60, // 1 minute default stale time
retry: 2,
refetchOnWindowFocus: true,
},
},
})
function App() {
return (
<QueryClientProvider client={queryClient}>
<YourApp />
<ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>
)
}
['entity', 'list'], ['entity', 'detail', id]// queryKeys.ts
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() to define queries once and reuse across components and loadersimport { queryOptions } from '@tanstack/react-query'
export const postQueryOptions = (id: string) =>
queryOptions({
queryKey: postKeys.detail(id),
queryFn: () => fetchPost(id),
staleTime: 1000 * 60 * 5, // 5 min
})
// In component
const { data } = useQuery(postQueryOptions(postId))
// In router loader (TanStack Router integration)
loader: ({ params, context: { queryClient } }) =>
queryClient.ensureQueryData(postQueryOptions(params.postId))
const {
data,
isLoading, // true only on first load with no cached data
isFetching, // true whenever a fetch is in-flight
isError,
error,
isSuccess,
} = useQuery({
queryKey: postKeys.detail(postId),
queryFn: () => fetchPost(postId),
enabled: !!postId, // disable query if params not ready
})
const { mutate, mutateAsync, isPending } = useMutation({
mutationFn: (newPost: CreatePostInput) => createPost(newPost),
onSuccess: (data) => {
// Invalidate and refetch
queryClient.invalidateQueries({ queryKey: postKeys.lists() })
toast.success('Post created!')
},
onError: (error) => {
toast.error(error.message)
},
})
// Usage
mutate({ title: 'Hello', body: '...' })
const queryClient = useQueryClient()
const mutation = useMutation({
mutationFn: updatePost,
onMutate: async (updatedPost) => {
await queryClient.cancelQueries({ queryKey: postKeys.detail(updatedPost.id) })
const previous = queryClient.getQueryData(postKeys.detail(updatedPost.id))
queryClient.setQueryData(postKeys.detail(updatedPost.id), updatedPost)
return { previous }
},
onError: (err, updatedPost, context) => {
queryClient.setQueryData(postKeys.detail(updatedPost.id), context?.previous)
},
onSettled: (_, __, updatedPost) => {
queryClient.invalidateQueries({ queryKey: postKeys.detail(updatedPost.id) })
},
})
const {
data,
fetchNextPage,
hasNextPage,
isFetchingNextPage,
} = useInfiniteQuery({
queryKey: postKeys.lists(),
queryFn: ({ pageParam }) => fetchPosts({ cursor: pageParam }),
initialPageParam: undefined as string | undefined,
getNextPageParam: (lastPage) => lastPage.nextCursor,
})
// data.pages is an array of page results — flatten for rendering
const allPosts = data?.pages.flatMap((page) => page.items) ?? []
// Hover prefetch
const handleMouseEnter = () => {
queryClient.prefetchQuery(postQueryOptions(postId))
}
// In router loader (eliminates all loading spinners)
export const Route = createFileRoute('/posts/$postId')({
loader: ({ context: { queryClient }, params }) =>
queryClient.ensureQueryData(postQueryOptions(params.postId)),
})
// Invalidate all post queries
queryClient.invalidateQueries({ queryKey: postKeys.all })
// Invalidate only post lists
queryClient.invalidateQueries({ queryKey: postKeys.lists() })
// Remove from cache entirely
queryClient.removeQueries({ queryKey: postKeys.detail(id) })
// Directly update cache without refetch
queryClient.setQueryData(postKeys.detail(id), newData)
useSuspenseQuery for Suspense-based data fetching (v5)<Suspense fallback={<Skeleton />}><ErrorBoundary> for error handling// No need to handle isLoading — Suspense handles it
const { data } = useSuspenseQuery(postQueryOptions(postId))
staleTime per query — defaults to 0 (always stale)select to transform/subscribe to only relevant slices of dataplaceholderData: keepPreviousData for pagination to avoid layout shiftsQueryClient inside components — instantiate once at app rootnotifyOnChangeProps to limit re-renders to only relevant data changesthrowOnError: true to bubble errors to the nearest ErrorBoundaryretry function for conditional retry logic (e.g., skip retry on 404)retry: (failureCount, error) => {
if (error.status === 404) return false
return failureCount < 3
},
queryFn return value explicitly or infer from typed API functionsQueryObserverResult<TData, TError> to type hook return valuesUseMutationResult<TData, TError, TVariables> for mutationsPublic domain (CC0 1.0) · by awesome-cursorrules contributors · source · posted by @OpenSourceBuffGuy on promptparty.com


Reverse-engineers a website section by section, writes component specs, and hands them to parallel builder agents in git worktrees to rebuild it.
agent-skill, orchestrator, parallel-agents, multi-agent, plan-then-execute, web-development, frontend, codebase-analysis, scaffolding, css, html, nextjs, typescript, git, mcp, claude-code, for-developers, for-designers, long-form, advanced, technical-spec, task-decomposition, structured-output, design-systems, ui-ux, tool-use, checklist, report, vibe-coding

Italian Terrace Cafe Candid Portrait
Generates a photorealistic candid shot of a woman in a white corset dress laughing at a sunny hotel terrace cafe, written as detailed JSON.
image-prompt, json-prompt, structured-output, photorealistic, portrait, woman, candid, fashion, cottagecore, natural-light, golden-hour, bokeh, summer, travel, cityscape, mountains, medium-shot, vibrant-colors, for-photographers, nano-banana, fashion-shoot, luxury

Night Street Photo With Leashed Cat
Generates a flash-lit night street photo of a blonde woman in a retro track jacket walking a hissing tabby cat on a leash.
image-prompt, json-prompt, nano-banana, structured-output, portrait, woman, animals, pet-portrait, night-scene, street-photography, candid, editorial, fashion, dramatic-lighting, photorealistic, vertical-format, medium-shot, graffiti, for-photographers, for-content-creators
Loading reviews…
Loading comments…