How to Do React Query Data Fetching on Claude Code

In this article

To do React Query data fetching on Claude Code, describe your data requirements in plain English and let Claude generate the useQuery hooks, query keys, and cache config automatically. This workflow is ideal for React developers who want production-ready TanStack Query boilerplate without leaving their editor. The main trade-off: Claude Code burns through usage tokens fast on large scaffolding tasks, so hitting a 5-hour lockout mid-PR is a real risk.

  • React Query (TanStack Query) has over 40,000 GitHub stars and is the de facto standard for async state in React apps.
  • Claude Code can generate full query hooks, including error states, loading skeletons, and retry logic, in a single prompt.
  • Usage resets on a rolling 5-hour window. One heavy scaffolding session can consume your entire quota.

What is React Query and why use it with Claude Code?

TanStack Query (React Query) handles server-state management: fetching, caching, synchronizing, and updating remote data. It replaces the useEffect + useState anti-pattern with a declarative API built around query keys and query functions.

Claude Code is well-suited to this library because React Query has a consistent, learnable API surface. Claude can scaffold the correct patterns reliably when given clear context: your endpoint, your response shape, and the caching behavior you want.

How to set up React Query in your project using Claude Code

Start a Claude Code session in your project root and run:

Install and configure TanStack Query v5. Add QueryClient and QueryClientProvider to src/main.tsx with sensible defaults: staleTime 60s, retry 2.

Claude will install @tanstack/react-query, create the QueryClient instance, and wrap your app. Ask it to also add @tanstack/react-query-devtools for development inspection.

  • staleTime: how long data is considered fresh (prevents redundant refetches)
  • gcTime (formerly cacheTime): how long unused cache entries stay in memory
  • retry: number of automatic retries on failure
  • refetchOnWindowFocus: set to false during development to reduce noise

How to generate useQuery hooks with Claude Code

The most effective prompt pattern is to describe your endpoint, expected response type, and caching intent together:

Create a useQuery hook for GET /api/users/:id. Response type is User { id, name, email, role }. Cache for 5 minutes. Export as useUser(id: string).

Claude will produce a typed hook with a structured query key (['users', id]), a typed queryFn, and the correct enabled guard for when id is undefined. It follows the TanStack Query key factory pattern if you ask it to.

Ask Claude to generate a query key factory

Query key collisions cause stale data bugs. Ask Claude to generate a centralized key factory:

Generate a query key factory for the users domain with keys for list, detail, and search queries.

This keeps keys consistent across hooks and makes cache invalidation predictable.

How to scaffold mutations and cache invalidation

Mutations are where React Query projects often get messy. Give Claude the full picture upfront:

Create a useMutation hook for POST /api/users. On success, invalidate ['users', 'list'] and redirect to /users/:id. Show optimistic update pattern.

Claude handles the onSuccess, onError, and onSettled callbacks, and uses queryClient.invalidateQueries correctly. The optimistic update pattern requires passing the previous snapshot to onMutate and rolling back in onError, which Claude can generate end-to-end if asked explicitly.

How to implement paginated and infinite queries

For paginated APIs, ask Claude to use useInfiniteQuery:

Implement useInfiniteQuery for GET /api/posts?page=1&limit=20. Use cursor-based pagination with nextCursor from the response. Add a "Load more" button component.

Claude will wire up getNextPageParam, flatten the pages array for rendering, and handle the isFetchingNextPage loading state. This is one of the more error-prone patterns to write manually, making it a strong case for using Claude Code.

How to use Claude Code slash commands during data fetching work

Claude Code's slash commands speed up the workflow:

  • /add-dir: add your src/hooks or src/queries directory to context so Claude understands existing patterns before generating new hooks.
  • /memory: store your API base URL, auth header pattern, and response envelope shape so you don't repeat them in every prompt.
  • /clear: reset context between unrelated features to reduce token consumption on large sessions.
  • /usage: check your current Claude Code usage balance mid-session so you know if you have enough quota to finish the task.

The /usage command is particularly important when scaffolding a full data layer. A single session generating queries, mutations, error boundaries, and tests can consume a significant portion of your 5-hour window. Check it before starting large tasks.

Practical prompting tips for React Query scaffolding

  • Provide the TypeScript types first. Paste your API response types before asking for hooks. Claude generates more accurate code when it knows the shape.
  • Specify the version. TanStack Query v4 and v5 have breaking differences (cacheTime vs gcTime, status shape). State @tanstack/react-query v5 explicitly.
  • Ask for tests in the same prompt. Request React Testing Library tests alongside each hook. This keeps token usage efficient compared to a separate follow-up session.
  • Use /memory for your error handling pattern. If your app uses a global toast system, store that context so every onError callback Claude generates uses it consistently.
  • Batch related hooks. Ask for all hooks in a domain (list, detail, create, update, delete) in one prompt to preserve context and reduce overhead.

How to avoid hitting usage limits during a React Query session

React Query scaffolding is token-intensive. A full data layer for a medium-sized app (10-15 endpoints, with mutations, optimistic updates, and tests) can consume a large chunk of your Claude Code usage window. Getting hit with a 5-hour lockout while wrapping up a PR is one of the most disruptive things that can happen mid-session.

You can check your current usage with the /usage command in Claude Code, or by visiting claude.ai/settings/usage. For a persistent, at-a-glance view without breaking flow, Usagebar lives in your macOS menu bar and shows your live usage percentage with alerts at 50%, 75%, and 90% so you can decide whether to continue or pace the session.

Usagebar also shows exactly when your 5-hour usage window resets, so you can plan which parts of a feature to tackle now versus after the reset. Credentials are stored in macOS Keychain, and the app uses a pay-what-you-want model with a free option for students.

Get Usagebar for instant download and start tracking your Claude Code usage without switching context.

Key takeaways

  1. Set up QueryClient with sensible defaults first, then build hooks incrementally by domain.
  2. Always specify TanStack Query version (v5) and provide TypeScript types upfront for accurate output.
  3. Use a query key factory to prevent cache collisions across hooks.
  4. Ask for mutations with full onSuccess/onError callbacks and cache invalidation in a single prompt.
  5. Use /memory to persist your API base URL, auth pattern, and error handling approach across prompts.
  6. Check /usage or use Usagebar before starting large scaffolding sessions to avoid a mid-session lockout.

Sources

Never Get Locked Out Mid-Task Again

Never hit your usage limits unexpectedly. Usagebar lives in your menu bar and shows your 5-hour and weekly limits at a glance.

Get Usagebar

$9 — one-time, lifetime updates