Home › React › TanStack Query v5 rules

TanStack Query v5 rules

Cursor rules for TanStack Query v5 in React: query keys, queryOptions, mutations, and cache invalidation.

CursorReact

How to use

Save this as .cursor/rules/tanstack-query.mdc in your repository root, commit it, and your agent will pick it up automatically. Edit the commands to match your project.

.cursor/rules/tanstack-query.mdcDownload  
---
description: TanStack Query v5 conventions
globs: ["src/**/*.{ts,tsx}"]
alwaysApply: false
---

# TanStack Query v5

- Define queries once with `queryOptions()` in `src/queries/<entity>.ts` and reuse them in `useQuery`, `useSuspenseQuery`, `prefetchQuery` and `ensureQueryData`.
- Query keys are arrays that start with the entity and include every variable the fetcher uses: `['todos', 'list', { status, page }]`. Keep a key factory per entity.
- The `queryFn` throws on non-2xx responses (check `res.ok`); never return error objects as data.
- Use v5 names: `isPending` (not `isLoading` for "no data yet"), `gcTime` (not `cacheTime`), `placeholderData: keepPreviousData` for pagination. Single object signature only.
- Mutations: `useMutation` then `queryClient.invalidateQueries({ queryKey: ['todos'] })` in `onSettled`. Use optimistic updates only when the UX needs them, with rollback in `onError`.
- Set a sensible `staleTime` per query instead of disabling refetching globally.
- Server state stays in Query. Don't copy query data into `useState` or a global store.
- Dependent queries use `enabled: !!id`.

## Don't
- Don't call `fetch` in `useEffect` for server data.
- Don't create a `QueryClient` inside a component render.

## Done when
Typecheck and tests pass; tests wrap components in a fresh `QueryClient` with `retry: false`.

Related rules

Astro content site rules

Cursor rules for Astro 5 sites with content collections, islands, and zero-JS-by-default pages.

CursorAstro

Chrome extension (Manifest V3) rules

Cursor rules for building Manifest V3 browser extensions with TypeScript and minimal permissions.

CursorChrome extensions

Cloudflare Agents SDK rules

Cursor rules for stateful AI agents on Cloudflare (agents package): Durable Object state, SQL, scheduling, and WebSockets.

CursorCloudflare Workers / Hono

Convex backend rules

Cursor rules for Convex backends: schema, validated queries/mutations/actions, indexes, and auth checks.

CursorConvex

Get new rules weekly

One email a week: fresh rule files, agent tips, and what's changing in Cursor, Claude Code and Copilot. Free, unsubscribe anytime.

Opens the Rulestack Newsletter on beehiiv in a new tab. Or subscribe directly on beehiiv.