Rule
0 installs · 0 said it worked
Cursor rules for writing TanStack Query v5 data-fetching code
Cursor rules file that makes the assistant follow TanStack Query v5 conventions: queryOptions helpers, query key factories, mutations with optimistic updates, infinite queries, and Suspense mode.
People use this for
- tanstack query v5 react data fetching
- react query optimistic updates pattern
- cursor rules for react query
- queryoptions helper typescript react
- infinite scroll react query code
- Name
cursor-rules-for-writing-tanstack-query-v5-data-fetching-code- Works with
- Cursor
- License
- CC0(as observed at the source)
- Version
- v1 · updated Nov 29, 2026
Imported on Nov 29, 2026 from github.com . License observed at the source on Nov 29, 2026: CC0.
Are you the author?Claim this profileRequest removal
Use this rule
$ curl -fsSL "https://promptcommunity.dev/api/v1/posts/cursor-rules-for-writing-tanstack-query-v5-data-fetching-code-vhsx/export/mdc" -o .cursor/rules/cursor-rules-for-writing-tanstack-query-v5-data-fetching-code.mdcThen open a new session; Cursor picks it up from .cursor/rules/.
Manual install
Save cursor-rules-for-writing-tanstack-query-v5-data-fetching-code.mdc as .cursor/rules/cursor-rules-for-writing-tanstack-query-v5-data-fetching-code.mdc for this project or ~/.cursor/rules/cursor-rules-for-writing-tanstack-query-v5-data-fetching-code.mdc for every project, then start a new session.
Rule
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:
useQueryonly accepts options object form — no positional args
QueryClient Setup
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
No result recorded yet. Added it? File a Tried-it report so the next person knows how it went in your editor.
Tried it
Reports from people who added this rule to their editor. They roll up into the badges above.
No one has filed a report yet. Try the prompt and be the first.
Related rules
- Cursor rules for writing TanStack Query v5 data-fetching code in React
Cursor rules that make the assistant an expert in TanStack Query v5 and TypeScript, covering query keys, queryOptions, mutations, optimistic updates, infinite queries, Suspense, prefetching, and error handling.
Coding · @patrickjs
- SQL Index Recommendation Reviewer for slow queries and schemas
Reviews a schema and slow SQL queries, proposes composite indexes in the right column order, flags non-sargable filters, and warns about duplicate, redundant, and low-selectivity indexes, with a stdlib Python helper.
Data & Finance · @f
- Convex backend coding rules for Cursor AI assistant
A Cursor rules file (.mdc) that guides the AI to write Convex backend code with current best practices: new function syntax, validators, function registration, references, pagination, schema, and query and action rules.
Coding · @patrickjs
- Cursor rules enforcing clean, readable, maintainable code practices
A Cursor .mdc rule file that guides the assistant toward clean code: named constants, meaningful names, sparing comments, single-purpose functions, DRY, language style standards, extracted conditionals, continuous refactoring, and version control.
Coding · @patrickjs
- Cursor rules for building Next.js App Router apps with TanStack Query v5
Cursor rules guiding the assistant on Next.js App Router data flow with TanStack Query v5: server prefetch with HydrationBoundary, Server Actions as mutations, optimistic updates, infinite queries, and when to use Server Components versus client queries.
Coding · @patrickjs
License: CC0v1 · published Nov 29, 2026
Comments
No comments yet. If you tried this prompt, say how it went.