[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M791X7QWERT1G043VGNP84ER":3,"skill-same:01M791X7QWERT1G043VGNP84ER":47},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":6,"ownerHtmlUrl":29,"ownerBlogUrl":30,"ownerDescription":31,"updatedAt":32,"install":33,"resources":46},"01M791X7QWERT1G043VGNP84ER","tanstack-query",null,"Powerful asynchronous state management, server-state utilities, and data fetching for TS\u002FJS, React, Vue, Solid, Svelte & Angular.","endalk200\u002Fartiflow","endalk200","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F44495881?v=4","01M6BYRJ2PAY7EXZ7DJF5VZ7DB","Endalkachew Biruk","01M791V154K6ZZGYPMJTA8FZ8Y",2,"MIT","https:\u002F\u002Fgithub.com\u002Fendalk200\u002Fartiflow\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Ftanstack-query\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: tanstack-query\ndescription: Powerful asynchronous state management, server-state utilities, and data fetching for TS\u002FJS, React, Vue, Solid, Svelte & Angular.\n---\n\n\n## Overview\n\nTanStack Query (formerly React Query) manages server state - data that lives on the server and needs to be fetched, cached, synchronized, and updated. It provides automatic caching, background refetching, stale-while-revalidate patterns, pagination, infinite scrolling, and optimistic updates out of the box.\n\n**Package:** `@tanstack\u002Freact-query`\n**Devtools:** `@tanstack\u002Freact-query-devtools`\n**Current Version:** v5\n\n## Installation\n\n```bash\nnpm install @tanstack\u002Freact-query\nnpm install -D @tanstack\u002Freact-query-devtools  # Optional\n```\n\n## Setup\n\n```tsx\nimport { QueryClient, QueryClientProvider } from '@tanstack\u002Freact-query'\nimport { ReactQueryDevtools } from '@tanstack\u002Freact-query-devtools'\n\nconst queryClient = new QueryClient({\n  defaultOptions: {\n    queries: {\n      staleTime: 1000 * 60, \u002F\u002F 1 minute\n      gcTime: 1000 * 60 * 5, \u002F\u002F 5 minutes (garbage collection)\n      retry: 3,\n      refetchOnWindowFocus: true,\n      refetchOnReconnect: true,\n    },\n  },\n})\n\nfunction App() {\n  return (\n    \u003CQueryClientProvider client={queryClient}>\n      \u003CYourApp \u002F>\n      \u003CReactQueryDevtools initialIsOpen={false} \u002F>\n    \u003C\u002FQueryClientProvider>\n  )\n}\n```\n\n## Core Concepts\n\n### Query Keys\n\nQuery keys uniquely identify cached data. They must be serializable arrays:\n\n```tsx\n\u002F\u002F Simple key\nuseQuery({ queryKey: ['todos'], queryFn: fetchTodos })\n\n\u002F\u002F With variables (dependency array pattern)\nuseQuery({ queryKey: ['todos', { status, page }], queryFn: fetchTodos })\n\n\u002F\u002F Hierarchical keys for invalidation\nuseQuery({ queryKey: ['todos', todoId], queryFn: () => fetchTodo(todoId) })\nuseQuery({ queryKey: ['todos', todoId, 'comments'], queryFn: () => fetchComments(todoId) })\n\n\u002F\u002F Invalidation matches prefixes:\n\u002F\u002F queryClient.invalidateQueries({ queryKey: ['todos'] })\n\u002F\u002F ^ Invalidates ALL queries starting with 'todos'\n```\n\n### Query Functions\n\n```tsx\n\u002F\u002F Query function receives a QueryFunctionContext\nuseQuery({\n  queryKey: ['todos', todoId],\n  queryFn: async ({ queryKey, signal, meta }) => {\n    const [_key, id] = queryKey\n    const response = await fetch(`\u002Fapi\u002Ftodos\u002F${id}`, { signal })\n    if (!response.ok) throw new Error('Failed to fetch')\n    return response.json()\n  },\n})\n\n\u002F\u002F Using the signal for automatic cancellation\nuseQuery({\n  queryKey: ['todos'],\n  queryFn: async ({ signal }) => {\n    const response = await fetch('\u002Fapi\u002Ftodos', { signal })\n    return response.json()\n  },\n})\n```\n\n### queryOptions Helper\n\nCreate reusable, type-safe query configurations:\n\n```tsx\nimport { queryOptions } from '@tanstack\u002Freact-query'\n\nexport const todosQueryOptions = queryOptions({\n  queryKey: ['todos'],\n  queryFn: fetchTodos,\n  staleTime: 5000,\n})\n\nexport const todoQueryOptions = (todoId: string) =>\n  queryOptions({\n    queryKey: ['todos', todoId],\n    queryFn: () => fetchTodo(todoId),\n    enabled: !!todoId,\n  })\n\n\u002F\u002F Usage\nconst { data } = useQuery(todosQueryOptions)\nconst { data } = useSuspenseQuery(todoQueryOptions(id))\nawait queryClient.prefetchQuery(todosQueryOptions)\n```\n\n## Queries (useQuery)\n\n### Basic Usage\n\n```tsx\nimport { useQuery } from '@tanstack\u002Freact-query'\n\nfunction Todos() {\n  const {\n    data,\n    error,\n    isLoading,      \u002F\u002F First load, no data yet\n    isFetching,     \u002F\u002F Any fetch in progress (including background)\n    isError,\n    isSuccess,\n    isPending,      \u002F\u002F No data yet (same as isLoading in most cases)\n    status,         \u002F\u002F 'pending' | 'error' | 'success'\n    fetchStatus,    \u002F\u002F 'fetching' | 'paused' | 'idle'\n    refetch,\n    isStale,\n    isPlaceholderData,\n    dataUpdatedAt,\n    errorUpdatedAt,\n  } = useQuery({\n    queryKey: ['todos'],\n    queryFn: fetchTodos,\n  })\n\n  if (isLoading) return \u003CSpinner \u002F>\n  if (isError) return \u003CError message={error.message} \u002F>\n  return \u003CTodoList todos={data} \u002F>\n}\n```\n\n### Query Options\n\n```tsx\nuseQuery({\n  queryKey: ['todos'],\n  queryFn: fetchTodos,\n\n  \u002F\u002F Freshness\n  staleTime: 5000,            \u002F\u002F ms data stays fresh (default: 0)\n  gcTime: 300000,             \u002F\u002F ms unused data stays in cache (default: 5 min)\n\n  \u002F\u002F Refetching\n  refetchInterval: 10000,     \u002F\u002F Poll every 10s\n  refetchIntervalInBackground: false, \u002F\u002F Don't poll when tab hidden\n  refetchOnMount: true,       \u002F\u002F Refetch on component mount if stale\n  refetchOnWindowFocus: true, \u002F\u002F Refetch on window focus if stale\n  refetchOnReconnect: true,   \u002F\u002F Refetch on network reconnect\n\n  \u002F\u002F Retry\n  retry: 3,                   \u002F\u002F Number of retries (or function)\n  retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),\n\n  \u002F\u002F Conditional\n  enabled: !!userId,          \u002F\u002F Only run when truthy\n\n  \u002F\u002F Initial\u002Fplaceholder data\n  initialData: () => cachedData,\n  initialDataUpdatedAt: Date.now() - 10000,\n  placeholderData: (previousData) => previousData, \u002F\u002F keepPreviousData pattern\n  placeholderData: initialTodos,\n\n  \u002F\u002F Transform\n  select: (data) => data.filter(todo => !todo.done),\n\n  \u002F\u002F Structural sharing (default: true)\n  structuralSharing: true,\n\n  \u002F\u002F Network mode\n  networkMode: 'online', \u002F\u002F 'online' | 'always' | 'offlineFirst'\n\n  \u002F\u002F Meta (accessible in query function context)\n  meta: { purpose: 'user-facing' },\n})\n```\n\n## Mutations (useMutation)\n\n### Basic Usage\n\n```tsx\nimport { useMutation, useQueryClient } from '@tanstack\u002Freact-query'\n\nfunction AddTodo() {\n  const queryClient = useQueryClient()\n\n  const mutation = useMutation({\n    mutationFn: (newTodo: { title: string }) => {\n      return fetch('\u002Fapi\u002Ftodos', {\n        method: 'POST',\n        body: JSON.stringify(newTodo),\n      }).then(res => res.json())\n    },\n    \u002F\u002F Lifecycle callbacks\n    onMutate: async (variables) => {\n      \u002F\u002F Called before mutationFn\n      \u002F\u002F Good for optimistic updates\n      return { previousTodos } \u002F\u002F context for onError\n    },\n    onSuccess: (data, variables, context) => {\n      \u002F\u002F Invalidate related queries\n      queryClient.invalidateQueries({ queryKey: ['todos'] })\n    },\n    onError: (error, variables, context) => {\n      \u002F\u002F Rollback optimistic updates\n      queryClient.setQueryData(['todos'], context.previousTodos)\n    },\n    onSettled: (data, error, variables, context) => {\n      \u002F\u002F Always runs (success or error)\n      queryClient.invalidateQueries({ queryKey: ['todos'] })\n    },\n  })\n\n  return (\n    \u003Cbutton\n      onClick={() => mutation.mutate({ title: 'New Todo' })}\n      disabled={mutation.isPending}\n    >\n      {mutation.isPending ? 'Adding...' : 'Add Todo'}\n    \u003C\u002Fbutton>\n  )\n}\n```\n\n### Mutation State\n\n```tsx\nconst {\n  mutate,         \u002F\u002F Fire-and-forget\n  mutateAsync,    \u002F\u002F Returns promise\n  isPending,      \u002F\u002F Mutation in progress\n  isError,\n  isSuccess,\n  isIdle,         \u002F\u002F Not yet fired\n  data,           \u002F\u002F Success response\n  error,          \u002F\u002F Error object\n  reset,          \u002F\u002F Reset state to idle\n  variables,      \u002F\u002F Variables passed to mutate\n  status,         \u002F\u002F 'idle' | 'pending' | 'error' | 'success'\n} = useMutation({ ... })\n```\n\n## Optimistic Updates\n\n```tsx\nconst mutation = useMutation({\n  mutationFn: updateTodo,\n  onMutate: async (newTodo) => {\n    \u002F\u002F 1. Cancel outgoing refetches\n    await queryClient.cancelQueries({ queryKey: ['todos', newTodo.id] })\n\n    \u002F\u002F 2. Snapshot previous value\n    const previousTodo = queryClient.getQueryData(['todos', newTodo.id])\n\n    \u002F\u002F 3. Optimistically update\n    queryClient.setQueryData(['todos', newTodo.id], newTodo)\n\n    \u002F\u002F 4. Return context for rollback\n    return { previousTodo }\n  },\n  onError: (err, newTodo, context) => {\n    \u002F\u002F Rollback on error\n    queryClient.setQueryData(['todos', newTodo.id], context.previousTodo)\n  },\n  onSettled: () => {\n    \u002F\u002F Always refetch to sync with server\n    queryClient.invalidateQueries({ queryKey: ['todos'] })\n  },\n})\n```\n\n### Optimistic Updates on Lists\n\n```tsx\nonMutate: async (newTodo) => {\n  await queryClient.cancelQueries({ queryKey: ['todos'] })\n  const previousTodos = queryClient.getQueryData(['todos'])\n\n  queryClient.setQueryData(['todos'], (old) => [...old, newTodo])\n\n  return { previousTodos }\n},\nonError: (err, newTodo, context) => {\n  queryClient.setQueryData(['todos'], context.previousTodos)\n},\n```\n\n## Query Invalidation\n\n```tsx\nconst queryClient = useQueryClient()\n\n\u002F\u002F Invalidate all queries\nqueryClient.invalidateQueries()\n\n\u002F\u002F Invalidate by prefix\nqueryClient.invalidateQueries({ queryKey: ['todos'] })\n\n\u002F\u002F Invalidate exact match\nqueryClient.invalidateQueries({ queryKey: ['todos', 1], exact: true })\n\n\u002F\u002F Invalidate with predicate\nqueryClient.invalidateQueries({\n  predicate: (query) =>\n    query.queryKey[0] === 'todos' && query.queryKey[1]?.status === 'done',\n})\n\n\u002F\u002F Invalidate and refetch immediately\nqueryClient.refetchQueries({ queryKey: ['todos'] })\n\n\u002F\u002F Remove from cache entirely\nqueryClient.removeQueries({ queryKey: ['todos', 1] })\n\n\u002F\u002F Reset to initial state\nqueryClient.resetQueries({ queryKey: ['todos'] })\n```\n\n## Infinite Queries\n\n```tsx\nimport { useInfiniteQuery } from '@tanstack\u002Freact-query'\n\nfunction InfiniteList() {\n  const {\n    data,\n    fetchNextPage,\n    fetchPreviousPage,\n    hasNextPage,\n    hasPreviousPage,\n    isFetchingNextPage,\n    isFetchingPreviousPage,\n  } = useInfiniteQuery({\n    queryKey: ['projects'],\n    queryFn: async ({ pageParam }) => {\n      const res = await fetch(`\u002Fapi\u002Fprojects?cursor=${pageParam}`)\n      return res.json()\n    },\n    initialPageParam: 0,\n    getNextPageParam: (lastPage, allPages, lastPageParam) => {\n      return lastPage.nextCursor ?? undefined \u002F\u002F undefined = no more pages\n    },\n    getPreviousPageParam: (firstPage, allPages, firstPageParam) => {\n      return firstPage.prevCursor ?? undefined\n    },\n    maxPages: 3, \u002F\u002F Keep max 3 pages in cache (for performance)\n  })\n\n  return (\n    \u003Cdiv>\n      {data.pages.map((page) =>\n        page.items.map((item) => \u003CItem key={item.id} item={item} \u002F>)\n      )}\n      \u003Cbutton\n        onClick={() => fetchNextPage()}\n        disabled={!hasNextPage || isFetchingNextPage}\n      >\n        {isFetchingNextPage ? 'Loading...' : hasNextPage ? 'Load More' : 'No more'}\n      \u003C\u002Fbutton>\n    \u003C\u002Fdiv>\n  )\n}\n```\n\n## Parallel Queries\n\n```tsx\n\u002F\u002F Multiple independent queries run in parallel automatically\nfunction Dashboard() {\n  const usersQuery = useQuery({ queryKey: ['users'], queryFn: fetchUsers })\n  const projectsQuery = useQuery({ queryKey: ['projects'], queryFn: fetchProjects })\n\n  \u002F\u002F Both fetch simultaneously\n}\n\n\u002F\u002F Dynamic parallel queries with useQueries\nfunction UserProjects({ userIds }) {\n  const queries = useQueries({\n    queries: userIds.map((id) => ({\n      queryKey: ['user', id],\n      queryFn: () => fetchUser(id),\n    })),\n    combine: (results) => ({\n      data: results.map(r => r.data),\n      pending: results.some(r => r.isPending),\n    }),\n  })\n}\n```\n\n## Dependent Queries\n\n```tsx\n\u002F\u002F Sequential queries using enabled\nfunction UserPosts({ userId }) {\n  const userQuery = useQuery({\n    queryKey: ['user', userId],\n    queryFn: () => fetchUser(userId),\n  })\n\n  const postsQuery = useQuery({\n    queryKey: ['posts', userId],\n    queryFn: () => fetchPostsByUser(userId),\n    enabled: !!userQuery.data, \u002F\u002F Only run when user is loaded\n  })\n}\n```\n\n## Paginated Queries\n\n```tsx\nfunction PaginatedList() {\n  const [page, setPage] = useState(1)\n\n  const { data, isPlaceholderData } = useQuery({\n    queryKey: ['todos', page],\n    queryFn: () => fetchTodos(page),\n    placeholderData: (previousData) => previousData, \u002F\u002F Keep showing old data\n  })\n\n  return (\n    \u003Cdiv style={{ opacity: isPlaceholderData ? 0.5 : 1 }}>\n      {data.items.map(item => \u003CItem key={item.id} item={item} \u002F>)}\n      \u003Cbutton\n        onClick={() => setPage(p => p + 1)}\n        disabled={isPlaceholderData || !data.hasMore}\n      >\n        Next\n      \u003C\u002Fbutton>\n    \u003C\u002Fdiv>\n  )\n}\n```\n\n## Suspense Integration\n\n```tsx\nimport { useSuspenseQuery, useSuspenseInfiniteQuery } from '@tanstack\u002Freact-query'\n\n\u002F\u002F Component will suspend until data is loaded\nfunction TodoList() {\n  const { data } = useSuspenseQuery({\n    queryKey: ['todos'],\n    queryFn: fetchTodos,\n  })\n  \u002F\u002F data is guaranteed to be defined here\n  return \u003Cul>{data.map(todo => \u003Cli key={todo.id}>{todo.title}\u003C\u002Fli>)}\u003C\u002Ful>\n}\n\n\u002F\u002F Wrap with Suspense boundary\nfunction App() {\n  return (\n    \u003CErrorBoundary fallback={\u003CError \u002F>}>\n      \u003CSuspense fallback={\u003CLoading \u002F>}>\n        \u003CTodoList \u002F>\n      \u003C\u002FSuspense>\n    \u003C\u002FErrorBoundary>\n  )\n}\n\n\u002F\u002F Multiple suspense queries (fetch in parallel)\nfunction Dashboard() {\n  const [{ data: users }, { data: projects }] = useSuspenseQueries({\n    queries: [\n      { queryKey: ['users'], queryFn: fetchUsers },\n      { queryKey: ['projects'], queryFn: fetchProjects },\n    ],\n  })\n}\n```\n\n## Prefetching\n\n```tsx\nconst queryClient = useQueryClient()\n\n\u002F\u002F Prefetch on hover\nfunction TodoLink({ todoId }) {\n  const prefetch = () => {\n    queryClient.prefetchQuery({\n      queryKey: ['todo', todoId],\n      queryFn: () => fetchTodo(todoId),\n      staleTime: 5000, \u002F\u002F Only prefetch if data older than 5s\n    })\n  }\n\n  return (\n    \u003CLink to={`\u002Ftodos\u002F${todoId}`} onMouseEnter={prefetch}>\n      Todo {todoId}\n    \u003C\u002FLink>\n  )\n}\n\n\u002F\u002F Prefetch in route loader (TanStack Router integration)\nexport const Route = createFileRoute('\u002Ftodos\u002F$todoId')({\n  loader: ({ context: { queryClient }, params: { todoId } }) =>\n    queryClient.ensureQueryData(todoQueryOptions(todoId)),\n})\n\n\u002F\u002F Prefetch infinite queries\nqueryClient.prefetchInfiniteQuery({\n  queryKey: ['projects'],\n  queryFn: fetchProjects,\n  initialPageParam: 0,\n  pages: 3, \u002F\u002F Prefetch first 3 pages\n})\n```\n\n## SSR & Hydration\n\n### Server-Side Prefetching\n\n```tsx\n\u002F\u002F Server component or loader\nimport { dehydrate, HydrationBoundary, QueryClient } from '@tanstack\u002Freact-query'\n\nasync function getServerSideProps() {\n  const queryClient = new QueryClient()\n\n  await queryClient.prefetchQuery({\n    queryKey: ['todos'],\n    queryFn: fetchTodos,\n  })\n\n  return {\n    props: {\n      dehydratedState: dehydrate(queryClient),\n    },\n  }\n}\n\nfunction Page({ dehydratedState }) {\n  return (\n    \u003CHydrationBoundary state={dehydratedState}>\n      \u003CTodos \u002F>\n    \u003C\u002FHydrationBoundary>\n  )\n}\n```\n\n### Streaming SSR (React Server Components)\n\n```tsx\nimport { dehydrate, HydrationBoundary } from '@tanstack\u002Freact-query'\nimport { makeQueryClient } from '.\u002Fquery-client'\n\nexport default async function Page() {\n  const queryClient = makeQueryClient()\n\n  \u002F\u002F Prefetch on server\n  await queryClient.prefetchQuery({\n    queryKey: ['todos'],\n    queryFn: fetchTodos,\n  })\n\n  return (\n    \u003CHydrationBoundary state={dehydrate(queryClient)}>\n      \u003CTodoList \u002F>\n    \u003C\u002FHydrationBoundary>\n  )\n}\n```\n\n## QueryClient API\n\n```tsx\nconst queryClient = useQueryClient()\n\n\u002F\u002F Get cached data\nqueryClient.getQueryData(['todos'])\n\n\u002F\u002F Set cached data\nqueryClient.setQueryData(['todos'], updatedTodos)\nqueryClient.setQueryData(['todos'], (old) => [...old, newTodo])\n\n\u002F\u002F Get query state\nqueryClient.getQueryState(['todos'])\n\n\u002F\u002F Check if fetching\nqueryClient.isFetching({ queryKey: ['todos'] })\nqueryClient.isMutating()\n\n\u002F\u002F Cancel queries\nqueryClient.cancelQueries({ queryKey: ['todos'] })\n\n\u002F\u002F Invalidate (marks stale, refetches active)\nqueryClient.invalidateQueries({ queryKey: ['todos'] })\n\n\u002F\u002F Refetch (force refetch even if fresh)\nqueryClient.refetchQueries({ queryKey: ['todos'] })\n\n\u002F\u002F Remove from cache\nqueryClient.removeQueries({ queryKey: ['todos'] })\n\n\u002F\u002F Reset to initial state\nqueryClient.resetQueries({ queryKey: ['todos'] })\n\n\u002F\u002F Clear entire cache\nqueryClient.clear()\n\n\u002F\u002F Prefetch\nqueryClient.prefetchQuery({ queryKey: ['todos'], queryFn: fetchTodos })\nqueryClient.ensureQueryData({ queryKey: ['todos'], queryFn: fetchTodos })\n\n\u002F\u002F Get\u002Fset defaults\nqueryClient.setQueryDefaults(['todos'], { staleTime: 10000 })\nqueryClient.getQueryDefaults(['todos'])\nqueryClient.setMutationDefaults(['addTodo'], { mutationFn: addTodo })\n```\n\n## Testing\n\n```tsx\nimport { renderHook, waitFor } from '@testing-library\u002Freact'\nimport { QueryClient, QueryClientProvider } from '@tanstack\u002Freact-query'\n\nfunction createWrapper() {\n  const queryClient = new QueryClient({\n    defaultOptions: {\n      queries: {\n        retry: false, \u002F\u002F Don't retry in tests\n        gcTime: Infinity, \u002F\u002F Prevent garbage collection during tests\n      },\n    },\n  })\n  return ({ children }) => (\n    \u003CQueryClientProvider client={queryClient}>\n      {children}\n    \u003C\u002FQueryClientProvider>\n  )\n}\n\ntest('fetches todos', async () => {\n  const { result } = renderHook(() => useQuery({\n    queryKey: ['todos'],\n    queryFn: fetchTodos,\n  }), { wrapper: createWrapper() })\n\n  await waitFor(() => expect(result.current.isSuccess).toBe(true))\n  expect(result.current.data).toEqual(expectedTodos)\n})\n\n\u002F\u002F Mock with setQueryData for component tests\ntest('renders todos', () => {\n  const queryClient = new QueryClient()\n  queryClient.setQueryData(['todos'], mockTodos)\n\n  render(\n    \u003CQueryClientProvider client={queryClient}>\n      \u003CTodoList \u002F>\n    \u003C\u002FQueryClientProvider>\n  )\n\n  expect(screen.getByText('Todo 1')).toBeInTheDocument()\n})\n```\n\n## TypeScript Patterns\n\n### Typing Query Functions\n\n```tsx\ninterface Todo {\n  id: number\n  title: string\n  completed: boolean\n}\n\n\u002F\u002F Type is inferred from queryFn return type\nconst { data } = useQuery({\n  queryKey: ['todos'],\n  queryFn: async (): Promise\u003CTodo[]> => {\n    const res = await fetch('\u002Fapi\u002Ftodos')\n    return res.json()\n  },\n})\n\u002F\u002F data: Todo[] | undefined\n\n\u002F\u002F With select\nconst { data } = useQuery({\n  queryKey: ['todos'],\n  queryFn: fetchTodos,\n  select: (data): string[] => data.map(t => t.title),\n})\n\u002F\u002F data: string[] | undefined\n```\n\n### Typing Errors\n\n```tsx\n\u002F\u002F Default error type is Error\nconst { error } = useQuery\u003CTodo[], AxiosError>({\n  queryKey: ['todos'],\n  queryFn: fetchTodos,\n})\n\n\u002F\u002F Or register globally\ndeclare module '@tanstack\u002Freact-query' {\n  interface Register {\n    defaultError: AxiosError\n  }\n}\n```\n\n### Query Options Pattern (Recommended)\n\n```tsx\nimport { queryOptions, infiniteQueryOptions } from '@tanstack\u002Freact-query'\n\nexport const todosOptions = queryOptions({\n  queryKey: ['todos'] as const,\n  queryFn: fetchTodos,\n  staleTime: 5000,\n})\n\nexport const todoOptions = (id: string) =>\n  queryOptions({\n    queryKey: ['todos', id] as const,\n    queryFn: () => fetchTodo(id),\n    enabled: !!id,\n  })\n\n\u002F\u002F Full type inference everywhere\nconst { data } = useQuery(todosOptions)\nconst { data } = useSuspenseQuery(todoOptions('123'))\nawait queryClient.ensureQueryData(todosOptions)\nqueryClient.invalidateQueries({ queryKey: todosOptions.queryKey })\n```\n\n## Advanced Patterns\n\n### Window Focus Refetching\n\n```tsx\n\u002F\u002F Disable globally\nconst queryClient = new QueryClient({\n  defaultOptions: {\n    queries: { refetchOnWindowFocus: false },\n  },\n})\n\n\u002F\u002F Custom focus manager\nimport { focusManager } from '@tanstack\u002Freact-query'\n\n\u002F\u002F For React Native\nfocusManager.setEventListener((handleFocus) => {\n  const subscription = AppState.addEventListener('change', (state) => {\n    handleFocus(state === 'active')\n  })\n  return () => subscription.remove()\n})\n```\n\n### Network Mode\n\n```tsx\nuseQuery({\n  queryKey: ['todos'],\n  queryFn: fetchTodos,\n  \u002F\u002F 'online' (default): only fetch when online\n  \u002F\u002F 'always': always fetch (useful for local-first)\n  \u002F\u002F 'offlineFirst': try fetch, use cache if offline\n  networkMode: 'offlineFirst',\n})\n```\n\n### Query Cancellation\n\n```tsx\nuseQuery({\n  queryKey: ['todos'],\n  queryFn: async ({ signal }) => {\n    \u002F\u002F signal is AbortSignal - automatically cancelled on unmount or key change\n    const res = await fetch('\u002Fapi\u002Ftodos', { signal })\n    return res.json()\n  },\n})\n\n\u002F\u002F Manual cancellation\nqueryClient.cancelQueries({ queryKey: ['todos'] })\n```\n\n### Persistence\n\n```tsx\nimport { persistQueryClient } from '@tanstack\u002Freact-query-persist-client'\nimport { createSyncStoragePersister } from '@tanstack\u002Fquery-sync-storage-persister'\n\nconst persister = createSyncStoragePersister({\n  storage: window.localStorage,\n})\n\npersistQueryClient({\n  queryClient,\n  persister,\n  maxAge: 1000 * 60 * 60 * 24, \u002F\u002F 24 hours\n})\n```\n\n## Best Practices\n\n1. **Use `queryOptions` helper** for type-safe, reusable query configurations\n2. **Structure query keys hierarchically** for granular invalidation\n3. **Set appropriate `staleTime`** - 0 means always refetch on mount (default), increase for less dynamic data\n4. **Use `placeholderData`** (not `initialData`) for keeping previous page data during pagination\n5. **Prefer `useSuspenseQuery`** when using Suspense boundaries for cleaner component code\n6. **Use `enabled`** for dependent queries, not conditional hook calls\n7. **Always invalidate after mutations** - don't rely solely on optimistic updates\n8. **Cancel queries in `onMutate`** before optimistic updates to prevent race conditions\n9. **Use `ensureQueryData`** in route loaders instead of `prefetchQuery` for immediate access\n10. **Set `retry: false` in tests** to avoid timeout issues\n11. **Don't destructure the query result** if you need to pass it around (breaks reactivity)\n12. **Use `select`** for derived data instead of transforming in the component\n13. **Keep query functions pure** - they should only fetch, not cause side effects\n14. **Use `gcTime: Infinity`** in tests to prevent cache cleanup during assertions\n\n## Common Pitfalls\n\n- Using `initialData` when you mean `placeholderData` (initialData counts as \"fresh\" data)\n- Not providing `initialPageParam` for infinite queries (required in v5)\n- Calling hooks conditionally (violates React rules)\n- Not cancelling queries before optimistic updates (race conditions)\n- Setting `staleTime` higher than `gcTime` (data gets garbage collected while \"fresh\")\n- Forgetting to wrap tests with `QueryClientProvider`\n- Using same `QueryClient` instance across tests (shared state)\n- Not awaiting `invalidateQueries` in mutation callbacks when order matters\n","## Overview\n\nTanStack Query (formerly React Query) manages server state - data that lives on the server and needs to be fetched, cached, synchronized, and updated. It provides automatic caching, background refetching, stale-while-revalidate patterns, pagination, infinite scrolling, and optimistic updates out of the box.\n\n**Package:** `@tanstack\u002Freact-query`\n**Devtools:** `@tanstack\u002Freact-query-devtools`\n**Current Version:** v5\n\n## Installation\n\n```bash\nnpm install @tanstack\u002Freact-query\nnpm install -D @tanstack\u002Freact-query-devtools  # Optional\n```\n\n## Setup\n\n```tsx\nimport { QueryClient, QueryClientProvider } from '@tanstack\u002Freact-query'\nimport { ReactQueryDevtools } from '@tanstack\u002Freact-query-devtools'\n\nconst queryClient = new QueryClient({\n  defaultOptions: {\n    queries: {\n      staleTime: 1000 * 60, \u002F\u002F 1 minute\n      gcTime: 1000 * 60 * 5, \u002F\u002F 5 minutes (garbage collection)\n      retry: 3,\n      refetchOnWindowFocus: true,\n      refetchOnReconnect: true,\n    },\n  },\n})\n\nfunction App() {\n  return (\n    \u003CQueryClientProvider client={queryClient}>\n      \u003CYourApp \u002F>\n      \u003CReactQueryDevtools initialIsOpen={false} \u002F>\n    \u003C\u002FQueryClientProvider>\n  )\n}\n```\n\n## Core Concepts\n\n### Query Keys\n\nQuery keys uniquely identify cached data. They must be serializable arrays:\n\n```tsx\n\u002F\u002F Simple key\nuseQuery({ queryKey: ['todos'], queryFn: fetchTodos })\n\n\u002F\u002F With variables (dependency array pattern)\nuseQuery({ queryKey: ['todos', { status, page }], queryFn: fetchTodos })\n\n\u002F\u002F Hierarchical keys for invalidation\nuseQuery({ queryKey: ['todos', todoId], queryFn: () => fetchTodo(todoId) })\nuseQuery({ queryKey: ['todos', todoId, 'comments'], queryFn: () => fetchComments(todoId) })\n\n\u002F\u002F Invalidation matches prefixes:\n\u002F\u002F queryClient.invalidateQueries({ queryKey: ['todos'] })\n\u002F\u002F ^ Invalidates ALL queries starting with 'todos'\n```\n\n### Query Functions\n\n```tsx\n\u002F\u002F Query function receives a QueryFunctionContext\nuseQuery({\n  queryKey: ['todos', todoId],\n  queryFn: async ({ queryKey, signal, meta }) => {\n    const [_key, id] = queryKey\n    const response = await fetch(`\u002Fapi\u002Ftodos\u002F${id}`, { signal })\n    if (!response.ok) throw new Error('Failed to fetch')\n    return response.json()\n  },\n})\n\n\u002F\u002F Using the signal for automatic cancellation\nuseQuery({\n  queryKey: ['todos'],\n  queryFn: async ({ signal }) => {\n    const response = await fetch('\u002Fapi\u002Ftodos', { signal })\n    return response.json()\n  },\n})\n```\n\n### queryOptions Helper\n\nCreate reusable, type-safe query configurations:\n\n```tsx\nimport { queryOptions } from '@tanstack\u002Freact-query'\n\nexport const todosQueryOptions = queryOptions({\n  queryKey: ['todos'],\n  queryFn: fetchTodos,\n  staleTime: 5000,\n})\n\nexport const todoQueryOptions = (todoId: string) =>\n  queryOptions({\n    queryKey: ['todos', todoId],\n    queryFn: () => fetchTodo(todoId),\n    enabled: !!todoId,\n  })\n\n\u002F\u002F Usage\nconst { data } = useQuery(todosQueryOptions)\nconst { data } = useSuspenseQuery(todoQueryOptions(id))\nawait queryClient.prefetchQuery(todosQueryOptions)\n```\n\n## Queries (useQuery)\n\n### Basic Usage\n\n```tsx\nimport { useQuery } from '@tanstack\u002Freact-query'\n\nfunction Todos() {\n  const {\n    data,\n    error,\n    isLoading,      \u002F\u002F First load, no data yet\n    isFetching,     \u002F\u002F Any fetch in progress (including background)\n    isError,\n    isSuccess,\n    isPending,      \u002F\u002F No data yet (same as isLoading in most cases)\n    status,         \u002F\u002F 'pending' | 'error' | 'success'\n    fetchStatus,    \u002F\u002F 'fetching' | 'paused' | 'idle'\n    refetch,\n    isStale,\n    isPlaceholderData,\n    dataUpdatedAt,\n    errorUpdatedAt,\n  } = useQuery({\n    queryKey: ['todos'],\n    queryFn: fetchTodos,\n  })\n\n  if (isLoading) return \u003CSpinner \u002F>\n  if (isError) return \u003CError message={error.message} \u002F>\n  return \u003CTodoList todos={data} \u002F>\n}\n```\n\n### Query Options\n\n```tsx\nuseQuery({\n  queryKey: ['todos'],\n  queryFn: fetchTodos,\n\n  \u002F\u002F Freshness\n  staleTime: 5000,            \u002F\u002F ms data stays fresh (default: 0)\n  gcTime: 300000,             \u002F\u002F ms unused data stays in cache (default: 5 min)\n\n  \u002F\u002F Refetching\n  refetchInterval: 10000,     \u002F\u002F Poll every 10s\n  refetchIntervalInBackground: false, \u002F\u002F Don't poll when tab hidden\n  refetchOnMount: true,       \u002F\u002F Refetch on component mount if stale\n  refetchOnWindowFocus: true, \u002F\u002F Refetch on window focus if stale\n  refetchOnReconnect: true,   \u002F\u002F Refetch on network reconnect\n\n  \u002F\u002F Retry\n  retry: 3,                   \u002F\u002F Number of retries (or function)\n  retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),\n\n  \u002F\u002F Conditional\n  enabled: !!userId,          \u002F\u002F Only run when truthy\n\n  \u002F\u002F Initial\u002Fplaceholder data\n  initialData: () => cachedData,\n  initialDataUpdatedAt: Date.now() - 10000,\n  placeholderData: (previousData) => previousData, \u002F\u002F keepPreviousData pattern\n  placeholderData: initialTodos,\n\n  \u002F\u002F Transform\n  select: (data) => data.filter(todo => !todo.done),\n\n  \u002F\u002F Structural sharing (default: true)\n  structuralSharing: true,\n\n  \u002F\u002F Network mode\n  networkMode: 'online', \u002F\u002F 'online' | 'always' | 'offlineFirst'\n\n  \u002F\u002F Meta (accessible in query function context)\n  meta: { purpose: 'user-facing' },\n})\n```\n\n## Mutations (useMutation)\n\n### Basic Usage\n\n```tsx\nimport { useMutation, useQueryClient } from '@tanstack\u002Freact-query'\n\nfunction AddTodo() {\n  const queryClient = useQueryClient()\n\n  const mutation = useMutation({\n    mutationFn: (newTodo: { title: string }) => {\n      return fetch('\u002Fapi\u002Ftodos', {\n        method: 'POST',\n        body: JSON.stringify(newTodo),\n      }).then(res => res.json())\n    },\n    \u002F\u002F Lifecycle callbacks\n    onMutate: async (variables) => {\n      \u002F\u002F Called before mutationFn\n      \u002F\u002F Good for optimistic updates\n      return { previousTodos } \u002F\u002F context for onError\n    },\n    onSuccess: (data, variables, context) => {\n      \u002F\u002F Invalidate related queries\n      queryClient.invalidateQueries({ queryKey: ['todos'] })\n    },\n    onError: (error, variables, context) => {\n      \u002F\u002F Rollback optimistic updates\n      queryClient.setQueryData(['todos'], context.previousTodos)\n    },\n    onSettled: (data, error, variables, context) => {\n      \u002F\u002F Always runs (success or error)\n      queryClient.invalidateQueries({ queryKey: ['todos'] })\n    },\n  })\n\n  return (\n    \u003Cbutton\n      onClick={() => mutation.mutate({ title: 'New Todo' })}\n      disabled={mutation.isPending}\n    >\n      {mutation.isPending ? 'Adding...' : 'Add Todo'}\n    \u003C\u002Fbutton>\n  )\n}\n```\n\n### Mutation State\n\n```tsx\nconst {\n  mutate,         \u002F\u002F Fire-and-forget\n  mutateAsync,    \u002F\u002F Returns promise\n  isPending,      \u002F\u002F Mutation in progress\n  isError,\n  isSuccess,\n  isIdle,         \u002F\u002F Not yet fired\n  data,           \u002F\u002F Success response\n  error,          \u002F\u002F Error object\n  reset,          \u002F\u002F Reset state to idle\n  variables,      \u002F\u002F Variables passed to mutate\n  status,         \u002F\u002F 'idle' | 'pending' | 'error' | 'success'\n} = useMutation({ ... })\n```\n\n## Optimistic Updates\n\n```tsx\nconst mutation = useMutation({\n  mutationFn: updateTodo,\n  onMutate: async (newTodo) => {\n    \u002F\u002F 1. Cancel outgoing refetches\n    await queryClient.cancelQueries({ queryKey: ['todos', newTodo.id] })\n\n    \u002F\u002F 2. Snapshot previous value\n    const previousTodo = queryClient.getQueryData(['todos', newTodo.id])\n\n    \u002F\u002F 3. Optimistically update\n    queryClient.setQueryData(['todos', newTodo.id], newTodo)\n\n    \u002F\u002F 4. Return context for rollback\n    return { previousTodo }\n  },\n  onError: (err, newTodo, context) => {\n    \u002F\u002F Rollback on error\n    queryClient.setQueryData(['todos', newTodo.id], context.previousTodo)\n  },\n  onSettled: () => {\n    \u002F\u002F Always refetch to sync with server\n    queryClient.invalidateQueries({ queryKey: ['todos'] })\n  },\n})\n```\n\n### Optimistic Updates on Lists\n\n```tsx\nonMutate: async (newTodo) => {\n  await queryClient.cancelQueries({ queryKey: ['todos'] })\n  const previousTodos = queryClient.getQueryData(['todos'])\n\n  queryClient.setQueryData(['todos'], (old) => [...old, newTodo])\n\n  return { previousTodos }\n},\nonError: (err, newTodo, context) => {\n  queryClient.setQueryData(['todos'], context.previousTodos)\n},\n```\n\n## Query Invalidation\n\n```tsx\nconst queryClient = useQueryClient()\n\n\u002F\u002F Invalidate all queries\nqueryClient.invalidateQueries()\n\n\u002F\u002F Invalidate by prefix\nqueryClient.invalidateQueries({ queryKey: ['todos'] })\n\n\u002F\u002F Invalidate exact match\nqueryClient.invalidateQueries({ queryKey: ['todos', 1], exact: true })\n\n\u002F\u002F Invalidate with predicate\nqueryClient.invalidateQueries({\n  predicate: (query) =>\n    query.queryKey[0] === 'todos' && query.queryKey[1]?.status === 'done',\n})\n\n\u002F\u002F Invalidate and refetch immediately\nqueryClient.refetchQueries({ queryKey: ['todos'] })\n\n\u002F\u002F Remove from cache entirely\nqueryClient.removeQueries({ queryKey: ['todos', 1] })\n\n\u002F\u002F Reset to initial state\nqueryClient.resetQueries({ queryKey: ['todos'] })\n```\n\n## Infinite Queries\n\n```tsx\nimport { useInfiniteQuery } from '@tanstack\u002Freact-query'\n\nfunction InfiniteList() {\n  const {\n    data,\n    fetchNextPage,\n    fetchPreviousPage,\n    hasNextPage,\n    hasPreviousPage,\n    isFetchingNextPage,\n    isFetchingPreviousPage,\n  } = useInfiniteQuery({\n    queryKey: ['projects'],\n    queryFn: async ({ pageParam }) => {\n      const res = await fetch(`\u002Fapi\u002Fprojects?cursor=${pageParam}`)\n      return res.json()\n    },\n    initialPageParam: 0,\n    getNextPageParam: (lastPage, allPages, lastPageParam) => {\n      return lastPage.nextCursor ?? undefined \u002F\u002F undefined = no more pages\n    },\n    getPreviousPageParam: (firstPage, allPages, firstPageParam) => {\n      return firstPage.prevCursor ?? undefined\n    },\n    maxPages: 3, \u002F\u002F Keep max 3 pages in cache (for performance)\n  })\n\n  return (\n    \u003Cdiv>\n      {data.pages.map((page) =>\n        page.items.map((item) => \u003CItem key={item.id} item={item} \u002F>)\n      )}\n      \u003Cbutton\n        onClick={() => fetchNextPage()}\n        disabled={!hasNextPage || isFetchingNextPage}\n      >\n        {isFetchingNextPage ? 'Loading...' : hasNextPage ? 'Load More' : 'No more'}\n      \u003C\u002Fbutton>\n    \u003C\u002Fdiv>\n  )\n}\n```\n\n## Parallel Queries\n\n```tsx\n\u002F\u002F Multiple independent queries run in parallel automatically\nfunction Dashboard() {\n  const usersQuery = useQuery({ queryKey: ['users'], queryFn: fetchUsers })\n  const projectsQuery = useQuery({ queryKey: ['projects'], queryFn: fetchProjects })\n\n  \u002F\u002F Both fetch simultaneously\n}\n\n\u002F\u002F Dynamic parallel queries with useQueries\nfunction UserProjects({ userIds }) {\n  const queries = useQueries({\n    queries: userIds.map((id) => ({\n      queryKey: ['user', id],\n      queryFn: () => fetchUser(id),\n    })),\n    combine: (results) => ({\n      data: results.map(r => r.data),\n      pending: results.some(r => r.isPending),\n    }),\n  })\n}\n```\n\n## Dependent Queries\n\n```tsx\n\u002F\u002F Sequential queries using enabled\nfunction UserPosts({ userId }) {\n  const userQuery = useQuery({\n    queryKey: ['user', userId],\n    queryFn: () => fetchUser(userId),\n  })\n\n  const postsQuery = useQuery({\n    queryKey: ['posts', userId],\n    queryFn: () => fetchPostsByUser(userId),\n    enabled: !!userQuery.data, \u002F\u002F Only run when user is loaded\n  })\n}\n```\n\n## Paginated Queries\n\n```tsx\nfunction PaginatedList() {\n  const [page, setPage] = useState(1)\n\n  const { data, isPlaceholderData } = useQuery({\n    queryKey: ['todos', page],\n    queryFn: () => fetchTodos(page),\n    placeholderData: (previousData) => previousData, \u002F\u002F Keep showing old data\n  })\n\n  return (\n    \u003Cdiv style={{ opacity: isPlaceholderData ? 0.5 : 1 }}>\n      {data.items.map(item => \u003CItem key={item.id} item={item} \u002F>)}\n      \u003Cbutton\n        onClick={() => setPage(p => p + 1)}\n        disabled={isPlaceholderData || !data.hasMore}\n      >\n        Next\n      \u003C\u002Fbutton>\n    \u003C\u002Fdiv>\n  )\n}\n```\n\n## Suspense Integration\n\n```tsx\nimport { useSuspenseQuery, useSuspenseInfiniteQuery } from '@tanstack\u002Freact-query'\n\n\u002F\u002F Component will suspend until data is loaded\nfunction TodoList() {\n  const { data } = useSuspenseQuery({\n    queryKey: ['todos'],\n    queryFn: fetchTodos,\n  })\n  \u002F\u002F data is guaranteed to be defined here\n  return \u003Cul>{data.map(todo => \u003Cli key={todo.id}>{todo.title}\u003C\u002Fli>)}\u003C\u002Ful>\n}\n\n\u002F\u002F Wrap with Suspense boundary\nfunction App() {\n  return (\n    \u003CErrorBoundary fallback={\u003CError \u002F>}>\n      \u003CSuspense fallback={\u003CLoading \u002F>}>\n        \u003CTodoList \u002F>\n      \u003C\u002FSuspense>\n    \u003C\u002FErrorBoundary>\n  )\n}\n\n\u002F\u002F Multiple suspense queries (fetch in parallel)\nfunction Dashboard() {\n  const [{ data: users }, { data: projects }] = useSuspenseQueries({\n    queries: [\n      { queryKey: ['users'], queryFn: fetchUsers },\n      { queryKey: ['projects'], queryFn: fetchProjects },\n    ],\n  })\n}\n```\n\n## Prefetching\n\n```tsx\nconst queryClient = useQueryClient()\n\n\u002F\u002F Prefetch on hover\nfunction TodoLink({ todoId }) {\n  const prefetch = () => {\n    queryClient.prefetchQuery({\n      queryKey: ['todo', todoId],\n      queryFn: () => fetchTodo(todoId),\n      staleTime: 5000, \u002F\u002F Only prefetch if data older than 5s\n    })\n  }\n\n  return (\n    \u003CLink to={`\u002Ftodos\u002F${todoId}`} onMouseEnter={prefetch}>\n      Todo {todoId}\n    \u003C\u002FLink>\n  )\n}\n\n\u002F\u002F Prefetch in route loader (TanStack Router integration)\nexport const Route = createFileRoute('\u002Ftodos\u002F$todoId')({\n  loader: ({ context: { queryClient }, params: { todoId } }) =>\n    queryClient.ensureQueryData(todoQueryOptions(todoId)),\n})\n\n\u002F\u002F Prefetch infinite queries\nqueryClient.prefetchInfiniteQuery({\n  queryKey: ['projects'],\n  queryFn: fetchProjects,\n  initialPageParam: 0,\n  pages: 3, \u002F\u002F Prefetch first 3 pages\n})\n```\n\n## SSR & Hydration\n\n### Server-Side Prefetching\n\n```tsx\n\u002F\u002F Server component or loader\nimport { dehydrate, HydrationBoundary, QueryClient } from '@tanstack\u002Freact-query'\n\nasync function getServerSideProps() {\n  const queryClient = new QueryClient()\n\n  await queryClient.prefetchQuery({\n    queryKey: ['todos'],\n    queryFn: fetchTodos,\n  })\n\n  return {\n    props: {\n      dehydratedState: dehydrate(queryClient),\n    },\n  }\n}\n\nfunction Page({ dehydratedState }) {\n  return (\n    \u003CHydrationBoundary state={dehydratedState}>\n      \u003CTodos \u002F>\n    \u003C\u002FHydrationBoundary>\n  )\n}\n```\n\n### Streaming SSR (React Server Components)\n\n```tsx\nimport { dehydrate, HydrationBoundary } from '@tanstack\u002Freact-query'\nimport { makeQueryClient } from '.\u002Fquery-client'\n\nexport default async function Page() {\n  const queryClient = makeQueryClient()\n\n  \u002F\u002F Prefetch on server\n  await queryClient.prefetchQuery({\n    queryKey: ['todos'],\n    queryFn: fetchTodos,\n  })\n\n  return (\n    \u003CHydrationBoundary state={dehydrate(queryClient)}>\n      \u003CTodoList \u002F>\n    \u003C\u002FHydrationBoundary>\n  )\n}\n```\n\n## QueryClient API\n\n```tsx\nconst queryClient = useQueryClient()\n\n\u002F\u002F Get cached data\nqueryClient.getQueryData(['todos'])\n\n\u002F\u002F Set cached data\nqueryClient.setQueryData(['todos'], updatedTodos)\nqueryClient.setQueryData(['todos'], (old) => [...old, newTodo])\n\n\u002F\u002F Get query state\nqueryClient.getQueryState(['todos'])\n\n\u002F\u002F Check if fetching\nqueryClient.isFetching({ queryKey: ['todos'] })\nqueryClient.isMutating()\n\n\u002F\u002F Cancel queries\nqueryClient.cancelQueries({ queryKey: ['todos'] })\n\n\u002F\u002F Invalidate (marks stale, refetches active)\nqueryClient.invalidateQueries({ queryKey: ['todos'] })\n\n\u002F\u002F Refetch (force refetch even if fresh)\nqueryClient.refetchQueries({ queryKey: ['todos'] })\n\n\u002F\u002F Remove from cache\nqueryClient.removeQueries({ queryKey: ['todos'] })\n\n\u002F\u002F Reset to initial state\nqueryClient.resetQueries({ queryKey: ['todos'] })\n\n\u002F\u002F Clear entire cache\nqueryClient.clear()\n\n\u002F\u002F Prefetch\nqueryClient.prefetchQuery({ queryKey: ['todos'], queryFn: fetchTodos })\nqueryClient.ensureQueryData({ queryKey: ['todos'], queryFn: fetchTodos })\n\n\u002F\u002F Get\u002Fset defaults\nqueryClient.setQueryDefaults(['todos'], { staleTime: 10000 })\nqueryClient.getQueryDefaults(['todos'])\nqueryClient.setMutationDefaults(['addTodo'], { mutationFn: addTodo })\n```\n\n## Testing\n\n```tsx\nimport { renderHook, waitFor } from '@testing-library\u002Freact'\nimport { QueryClient, QueryClientProvider } from '@tanstack\u002Freact-query'\n\nfunction createWrapper() {\n  const queryClient = new QueryClient({\n    defaultOptions: {\n      queries: {\n        retry: false, \u002F\u002F Don't retry in tests\n        gcTime: Infinity, \u002F\u002F Prevent garbage collection during tests\n      },\n    },\n  })\n  return ({ children }) => (\n    \u003CQueryClientProvider client={queryClient}>\n      {children}\n    \u003C\u002FQueryClientProvider>\n  )\n}\n\ntest('fetches todos', async () => {\n  const { result } = renderHook(() => useQuery({\n    queryKey: ['todos'],\n    queryFn: fetchTodos,\n  }), { wrapper: createWrapper() })\n\n  await waitFor(() => expect(result.current.isSuccess).toBe(true))\n  expect(result.current.data).toEqual(expectedTodos)\n})\n\n\u002F\u002F Mock with setQueryData for component tests\ntest('renders todos', () => {\n  const queryClient = new QueryClient()\n  queryClient.setQueryData(['todos'], mockTodos)\n\n  render(\n    \u003CQueryClientProvider client={queryClient}>\n      \u003CTodoList \u002F>\n    \u003C\u002FQueryClientProvider>\n  )\n\n  expect(screen.getByText('Todo 1')).toBeInTheDocument()\n})\n```\n\n## TypeScript Patterns\n\n### Typing Query Functions\n\n```tsx\ninterface Todo {\n  id: number\n  title: string\n  completed: boolean\n}\n\n\u002F\u002F Type is inferred from queryFn return type\nconst { data } = useQuery({\n  queryKey: ['todos'],\n  queryFn: async (): Promise\u003CTodo[]> => {\n    const res = await fetch('\u002Fapi\u002Ftodos')\n    return res.json()\n  },\n})\n\u002F\u002F data: Todo[] | undefined\n\n\u002F\u002F With select\nconst { data } = useQuery({\n  queryKey: ['todos'],\n  queryFn: fetchTodos,\n  select: (data): string[] => data.map(t => t.title),\n})\n\u002F\u002F data: string[] | undefined\n```\n\n### Typing Errors\n\n```tsx\n\u002F\u002F Default error type is Error\nconst { error } = useQuery\u003CTodo[], AxiosError>({\n  queryKey: ['todos'],\n  queryFn: fetchTodos,\n})\n\n\u002F\u002F Or register globally\ndeclare module '@tanstack\u002Freact-query' {\n  interface Register {\n    defaultError: AxiosError\n  }\n}\n```\n\n### Query Options Pattern (Recommended)\n\n```tsx\nimport { queryOptions, infiniteQueryOptions } from '@tanstack\u002Freact-query'\n\nexport const todosOptions = queryOptions({\n  queryKey: ['todos'] as const,\n  queryFn: fetchTodos,\n  staleTime: 5000,\n})\n\nexport const todoOptions = (id: string) =>\n  queryOptions({\n    queryKey: ['todos', id] as const,\n    queryFn: () => fetchTodo(id),\n    enabled: !!id,\n  })\n\n\u002F\u002F Full type inference everywhere\nconst { data } = useQuery(todosOptions)\nconst { data } = useSuspenseQuery(todoOptions('123'))\nawait queryClient.ensureQueryData(todosOptions)\nqueryClient.invalidateQueries({ queryKey: todosOptions.queryKey })\n```\n\n## Advanced Patterns\n\n### Window Focus Refetching\n\n```tsx\n\u002F\u002F Disable globally\nconst queryClient = new QueryClient({\n  defaultOptions: {\n    queries: { refetchOnWindowFocus: false },\n  },\n})\n\n\u002F\u002F Custom focus manager\nimport { focusManager } from '@tanstack\u002Freact-query'\n\n\u002F\u002F For React Native\nfocusManager.setEventListener((handleFocus) => {\n  const subscription = AppState.addEventListener('change', (state) => {\n    handleFocus(state === 'active')\n  })\n  return () => subscription.remove()\n})\n```\n\n### Network Mode\n\n```tsx\nuseQuery({\n  queryKey: ['todos'],\n  queryFn: fetchTodos,\n  \u002F\u002F 'online' (default): only fetch when online\n  \u002F\u002F 'always': always fetch (useful for local-first)\n  \u002F\u002F 'offlineFirst': try fetch, use cache if offline\n  networkMode: 'offlineFirst',\n})\n```\n\n### Query Cancellation\n\n```tsx\nuseQuery({\n  queryKey: ['todos'],\n  queryFn: async ({ signal }) => {\n    \u002F\u002F signal is AbortSignal - automatically cancelled on unmount or key change\n    const res = await fetch('\u002Fapi\u002Ftodos', { signal })\n    return res.json()\n  },\n})\n\n\u002F\u002F Manual cancellation\nqueryClient.cancelQueries({ queryKey: ['todos'] })\n```\n\n### Persistence\n\n```tsx\nimport { persistQueryClient } from '@tanstack\u002Freact-query-persist-client'\nimport { createSyncStoragePersister } from '@tanstack\u002Fquery-sync-storage-persister'\n\nconst persister = createSyncStoragePersister({\n  storage: window.localStorage,\n})\n\npersistQueryClient({\n  queryClient,\n  persister,\n  maxAge: 1000 * 60 * 60 * 24, \u002F\u002F 24 hours\n})\n```\n\n## Best Practices\n\n1. **Use `queryOptions` helper** for type-safe, reusable query configurations\n2. **Structure query keys hierarchically** for granular invalidation\n3. **Set appropriate `staleTime`** - 0 means always refetch on mount (default), increase for less dynamic data\n4. **Use `placeholderData`** (not `initialData`) for keeping previous page data during pagination\n5. **Prefer `useSuspenseQuery`** when using Suspense boundaries for cleaner component code\n6. **Use `enabled`** for dependent queries, not conditional hook calls\n7. **Always invalidate after mutations** - don't rely solely on optimistic updates\n8. **Cancel queries in `onMutate`** before optimistic updates to prevent race conditions\n9. **Use `ensureQueryData`** in route loaders instead of `prefetchQuery` for immediate access\n10. **Set `retry: false` in tests** to avoid timeout issues\n11. **Don't destructure the query result** if you need to pass it around (breaks reactivity)\n12. **Use `select`** for derived data instead of transforming in the component\n13. **Keep query functions pure** - they should only fetch, not cause side effects\n14. **Use `gcTime: Infinity`** in tests to prevent cache cleanup during assertions\n\n## Common Pitfalls\n\n- Using `initialData` when you mean `placeholderData` (initialData counts as \"fresh\" data)\n- Not providing `initialPageParam` for infinite queries (required in v5)\n- Calling hooks conditionally (violates React rules)\n- Not cancelling queries before optimistic updates (race conditions)\n- Setting `staleTime` higher than `gcTime` (data gets garbage collected while \"fresh\")\n- Forgetting to wrap tests with `QueryClientProvider`\n- Using same `QueryClient` instance across tests (shared state)\n- Not awaiting `invalidateQueries` in mutation callbacks when order matters\n",{"name":5,"description":7},"main","c05ef3c037b0f9c253f339c951b487b9118ad69b",".agents\u002Fskills\u002Ftanstack-query",0,"https:\u002F\u002Fgithub.com\u002Fendalk200\u002Fartiflow","https:\u002F\u002Fgithub.com\u002Fendalk200","endalk200.com","Senior Software Engineer & Technical Lead","2026-11-03 15:10:49",{"source":8,"skillName":5,"commands":34,"prompt":44,"zipAvailable":45},[35,38,41],{"tool":36,"command":37},"npx","npx skills add endalk200\u002Fartiflow --skill tanstack-query",{"tool":39,"command":40},"bunx","bunx skills add endalk200\u002Fartiflow --skill tanstack-query",{"tool":42,"command":43},"pnpm","pnpm dlx skills add endalk200\u002Fartiflow --skill tanstack-query","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fendalk200\u002Fartiflow\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Ftanstack-query\u002FSKILL.md",true,[],[48,55,62,69,76,83],{"skillNo":49,"name":50,"nameZh":6,"description":51,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":52,"categories":53,"keywords":54,"publishedAt":19},"01M791YFNVRKXWX13VFE5KJ54S","artiflow","Publish a polished visual Artifact for the current plan, report, review, or explanation.","https:\u002F\u002Fgithub.com\u002Fendalk200\u002Fartiflow\u002Fblob\u002Fmain\u002Fskills\u002Fartiflow\u002FSKILL.md",[],[],{"skillNo":56,"name":57,"nameZh":6,"description":58,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":59,"categories":60,"keywords":61,"publishedAt":19},"01M791YDNX6GBGJJS7QHTN767T","writing-for-agents","Writing documents for agents. Use when creating or editing skills, or modifying AGENTS.md or CLAUDE.md.","https:\u002F\u002Fgithub.com\u002Fendalk200\u002Fartiflow\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fwriting-for-agents\u002FSKILL.md",[],[],{"skillNo":63,"name":64,"nameZh":6,"description":65,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":66,"categories":67,"keywords":68,"publishedAt":19},"01M791YARDC91FEWW5R8NH6QBT","wayfinder","Plan a huge chunk of work — more than one agent session can hold — as a shared map of decision tickets on your issue tracker, and resolve them one at a time until the way to the destination is clear.","https:\u002F\u002Fgithub.com\u002Fendalk200\u002Fartiflow\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fwayfinder\u002FSKILL.md",[],[],{"skillNo":70,"name":71,"nameZh":6,"description":72,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":19},"01M791Y98HBXMVR6F9T9DF3M1E","wait-what","Stop. That last message did not land — re-pitch it.","https:\u002F\u002Fgithub.com\u002Fendalk200\u002Fartiflow\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fwait-what\u002FSKILL.md",[],[],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":19},"01M791Y0DNPW30WKXJ0N3YH0MN","turborepo","Turborepo monorepo build system guidance. Triggers on: turbo.json, task pipelines,\ndependsOn, caching, remote cache, the \"turbo\" CLI, --filter, --affected, CI optimization, environment\nvariables, internal packages, monorepo structure\u002Fbest practices, and boundaries.\n\nUse when user: configures tasks\u002Fworkflows\u002Fpipelines, creates packages, sets up\nmonorepo, shares code between apps, runs changed\u002Faffected packages, debugs cache,\nor has apps\u002Fpackages directories.","https:\u002F\u002Fgithub.com\u002Fendalk200\u002Fartiflow\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Fturborepo\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":19},"01M791XVV64WSJWC5JQSQ4F34Q","triage","Move issues and external pull requests through triage roles — categorise, verify, grill if needed, and write agent-ready briefs.","https:\u002F\u002Fgithub.com\u002Fendalk200\u002Fartiflow\u002Fblob\u002Fmain\u002F.agents\u002Fskills\u002Ftriage\u002FSKILL.md",[],[]]