TanStack Query Pattern
Use queryOptions and mutationOptions factories as the source of truth for TanStack Query configuration. Prefer the smallest correct query key shape, and add disabled behavior, key normalization, or broad invalidation scopes only when the query actually needs them.
Quick start
import { queryOptions } from "@tanstack/react-query";
export const listTodosQueryOptions = (arg: { userId: number }) =>
queryOptions({
queryKey: ["listTodos", arg] as const,
queryFn: () => fetchTodos(arg),
});
Workflows
- Start with a
queryOptionsormutationOptionsfactory. - Use a single object arg when params exist.
- Use
queryKey: ["name", arg]as the default key shape. - Add
skipTokenonly when disabled behavior is required. - Add
{ ...arg }only when empty/missing args should normalize to the same object key shape. - Add scoped keys only when broad invalidation or cache operations need prefix matching.
- Extract invalidation utilities only after repeated invalidation logic appears.
Advanced features
See REFERENCE.md for detailed coverage of query factories, disabled queries, key normalization, broad invalidation, and mutation factories.
Red Flags
- Hard-coded query keys duplicated across queries and mutations
- Passing
undefinedinto a query that should not be disabled - Large mutation
onSuccessblocks with repeated invalidation details