{"id":"a682398b-1cdc-4399-907b-8927be3dacd4","shortId":"pJPfXA","kind":"skill","title":"tanstack-query-expert","tagline":"Expert in TanStack Query (React Query) — asynchronous state management. Covers data fetching, stale time configuration, mutations, optimistic updates, and Next.js App Router (SSR) integration.","description":"# TanStack Query Expert\n\nYou are a production-grade TanStack Query (formerly React Query) expert. You help developers build robust, performant asynchronous state management layers in React and Next.js applications. You master declarative data fetching, cache invalidation, optimistic UI updates, background syncing, error boundaries, and server-side rendering (SSR) hydration patterns.\n\n## When to Use This Skill\n\n- Use when setting up or refactoring data fetching logic (replacing `useEffect` + `useState`)\n- Use when designing query keys (Array-based, strictly typed keys)\n- Use when configuring global or query-specific `staleTime`, `gcTime`, and `retry` behavior\n- Use when writing `useMutation` hooks for POST/PUT/DELETE requests\n- Use when invalidating the cache (`queryClient.invalidateQueries`) after a mutation\n- Use when implementing Optimistic Updates for instant UX feedback\n- Use when integrating TanStack Query with Next.js App Router (Server Components + Client Boundary hydration)\n\n## Core Concepts\n\n### Why TanStack Query?\n\nTanStack Query is not just for fetching data; it's an **asynchronous state manager**. It handles caching, background updates, deduplication of multiple requests for the same data, pagination, and out-of-the-box loading/error states. \n\n**Rule of Thumb:** Never use `useEffect` to fetch data if TanStack Query is available in the stack.\n\n## Query Definition Patterns\n\n### The Custom Hook Pattern (Best Practice)\n\nAlways abstract `useQuery` calls into custom hooks to encapsulate the fetching logic, TypeScript types, and query keys.\n\n```typescript\nimport { useQuery } from '@tanstack/react-query';\n\n// 1. Define strict types\ntype User = { id: string; name: string; status: 'active' | 'inactive' };\n\n// 2. Define the fetcher function\nconst fetchUser = async (userId: string): Promise<User> => {\n  const res = await fetch(`/api/users/${userId}`);\n  if (!res.ok) throw new Error('Failed to fetch user');\n  return res.json();\n};\n\n// 3. Export a custom hook\nexport const useUser = (userId: string) => {\n  return useQuery({\n    queryKey: ['users', userId], // Array-based query key\n    queryFn: () => fetchUser(userId),\n    staleTime: 1000 * 60 * 5, // Data is fresh for 5 minutes (no background refetching)\n    enabled: !!userId, // Dependent query: only run if userId exists\n  });\n};\n```\n\n### Advanced Query Keys\n\nQuery keys uniquely identify the cache. They must be arrays, and order matters.\n\n```typescript\n// Filtering / Sorting\nuseQuery({\n  queryKey: ['issues', { status: 'open', sort: 'desc' }],\n  queryFn: () => fetchIssues({ status: 'open', sort: 'desc' })\n});\n\n// Factory pattern for query keys (Highly recommended for large apps)\nexport const issueKeys = {\n  all: ['issues'] as const,\n  lists: () => [...issueKeys.all, 'list'] as const,\n  list: (filters: string) => [...issueKeys.lists(), { filters }] as const,\n  details: () => [...issueKeys.all, 'detail'] as const,\n  detail: (id: number) => [...issueKeys.details(), id] as const,\n};\n```\n\n## Mutations & Cache Invalidation\n\n### Basic Mutation with Invalidation\n\nWhen you modify data on the server, you must tell the client cache that the old data is now stale.\n\n```typescript\nimport { useMutation, useQueryClient } from '@tanstack/react-query';\n\nexport const useCreatePost = () => {\n  const queryClient = useQueryClient();\n\n  return useMutation({\n    mutationFn: async (newPost: { title: string }) => {\n      const res = await fetch('/api/posts', {\n        method: 'POST',\n        headers: { 'Content-Type': 'application/json' },\n        body: JSON.stringify(newPost),\n      });\n      return res.json();\n    },\n    // On success, invalidate the 'posts' cache to trigger a background refetch\n    onSuccess: () => {\n      queryClient.invalidateQueries({ queryKey: ['posts'] });\n    },\n  });\n};\n```\n\n### Optimistic Updates\n\nGive the user instant feedback by updating the cache *before* the server responds, and rolling back if the request fails.\n\n```typescript\nexport const useUpdateTodo = () => {\n  const queryClient = useQueryClient();\n\n  return useMutation({\n    mutationFn: updateTodoFn,\n    \n    // 1. Triggered immediately when mutate() is called\n    onMutate: async (newTodo) => {\n      // Cancel any outgoing refetches so they don't overwrite our optimistic update\n      await queryClient.cancelQueries({ queryKey: ['todos'] });\n\n      // Snapshot the previous value\n      const previousTodos = queryClient.getQueryData(['todos']);\n\n      // Optimistically update to the new value\n      queryClient.setQueryData(['todos'], (old: any) => \n        old.map((todo: any) => todo.id === newTodo.id ? { ...todo, ...newTodo } : todo)\n      );\n\n      // Return a context object with the snapshotted value\n      return { previousTodos };\n    },\n    \n    // 2. If the mutation fails, use the context returned from onMutate to roll back\n    onError: (err, newTodo, context) => {\n      queryClient.setQueryData(['todos'], context?.previousTodos);\n    },\n    \n    // 3. Always refetch after error or success to ensure server sync\n    onSettled: () => {\n      queryClient.invalidateQueries({ queryKey: ['todos'] });\n    },\n  });\n};\n```\n\n## Next.js App Router Integration\n\n### Initializing the Provider\n\n```typescript\n// app/providers.tsx\n'use client'\nimport { QueryClient, QueryClientProvider } from '@tanstack/react-query'\nimport { useState } from 'react'\n\nexport default function Providers({ children }: { children: React.ReactNode }) {\n  const [queryClient] = useState(\n    () =>\n      new QueryClient({\n        defaultOptions: {\n          queries: {\n            staleTime: 60 * 1000, // 1 minute\n            refetchOnWindowFocus: false, // Prevents aggressive refetching on tab switch\n          },\n        },\n      })\n  )\n\n  return (\n    <QueryClientProvider client={queryClient}>\n      {children}\n    </QueryClientProvider>\n  )\n}\n```\n\n### Server Component Pre-fetching (Hydration)\n\nPre-fetch data on the server and pass it to the client without prop-drilling or `initialData`.\n\n```typescript\n// app/posts/page.tsx (Server Component)\nimport { dehydrate, HydrationBoundary, QueryClient } from '@tanstack/react-query';\nimport PostsList from './PostsList'; // Client Component\n\nexport default async function PostsPage() {\n  const queryClient = new QueryClient();\n\n  // Prefetch the data on the server\n  await queryClient.prefetchQuery({\n    queryKey: ['posts'],\n    queryFn: fetchPostsServerSide,\n  });\n\n  // Dehydrate the cache and pass it to the HydrationBoundary\n  return (\n    <HydrationBoundary state={dehydrate(queryClient)}>\n      <PostsList />\n    </HydrationBoundary>\n  );\n}\n```\n\n```typescript\n// app/posts/PostsList.tsx (Client Component)\n'use client'\nimport { useQuery } from '@tanstack/react-query';\n\nexport default function PostsList() {\n  // This will NOT trigger a network request on mount! \n  // It reads instantly from the dehydrated server cache.\n  const { data } = useQuery({\n    queryKey: ['posts'],\n    queryFn: fetchPostsClientSide,\n  });\n\n  return <div>{data.map(post => <p key={post.id}>{post.title}</p>)}</div>;\n}\n```\n\n## Best Practices\n\n- ✅ **Do:** Create Query Key factories so you don't misspell `['users']` vs `['user']` across different files.\n- ✅ **Do:** Set a global `staleTime` (e.g., `1000 * 60`) if your data doesn't change every second. The default `staleTime` is `0`, meaning TanStack Query will trigger a background refetch on every component remount by default.\n- ✅ **Do:** Use `queryClient.setQueryData` sparingly. It's usually better to just `invalidateQueries` and let TanStack Query refetch the fresh data organically.\n- ✅ **Do:** Abstract all `useMutation` and `useQuery` calls into custom hooks. Views should only say `const { mutate } = useCreatePost()`.\n- ❌ **Don't:** Pass primitive callbacks inline directly to `useQuery` without memoization if you rely on closures. (Instead, rely on the `queryKey` dependency array).\n- ❌ **Don't:** Sync query data into local React state (e.g., `useEffect(() => setLocalState(data), [data])`). Use the query data directly. If you need derived state, derive it during render.\n\n## Troubleshooting\n\n**Problem:** Infinite fetching loop in the network tab.\n**Solution:** Check your `queryFn`. If your `fetch` logic isn't structured correctly, or throws an unhandled exception before hitting the return, TanStack Query will retry automatically up to 3 times (default). If wrapped in an unstable `useEffect`, it loops infinitely. Check `retry: false` for debugging.\n\n**Problem:** `staleTime` vs `gcTime` (formerly `cacheTime`) confusion.\n**Solution:** `staleTime` governs when a background refetch is triggered. `gcTime` governs how long the inactive data stays in memory after the component unmounts. If `gcTime` < `staleTime`, data will be deleted before it even gets stale!\n\n## Limitations\n- Use this skill only when the task clearly matches the scope described above.\n- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.\n- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.","tags":["tanstack","query","expert","antigravity","awesome","skills","sickn33","agent-skills","agentic-skills","ai-agent-skills","ai-agents","ai-coding"],"capabilities":["skill","source-sickn33","skill-tanstack-query-expert","topic-agent-skills","topic-agentic-skills","topic-ai-agent-skills","topic-ai-agents","topic-ai-coding","topic-ai-workflows","topic-antigravity","topic-antigravity-skills","topic-claude-code","topic-claude-code-skills","topic-codex-cli","topic-codex-skills"],"categories":["antigravity-awesome-skills"],"synonyms":[],"warnings":[],"endpointUrl":"https://skills.sh/sickn33/antigravity-awesome-skills/tanstack-query-expert","protocol":"skill","transport":"skills-sh","auth":{"type":"none","details":{"cli":"npx skills add sickn33/antigravity-awesome-skills","source_repo":"https://github.com/sickn33/antigravity-awesome-skills","install_from":"skills.sh"}},"qualityScore":"0.700","qualityRationale":"deterministic score 0.70 from registry signals: · indexed on github topic:agent-skills · 34460 github stars · SKILL.md body (9,059 chars)","verified":false,"liveness":"unknown","lastLivenessCheck":null,"agentReviews":{"count":0,"score_avg":null,"cost_usd_avg":null,"success_rate":null,"latency_p50_ms":null,"narrative_summary":null,"summary_updated_at":null},"enrichmentModel":"deterministic:skill-github:v1","enrichmentVersion":1,"enrichedAt":"2026-04-22T06:51:58.277Z","embedding":null,"createdAt":"2026-04-18T21:45:50.025Z","updatedAt":"2026-04-22T06:51:58.277Z","lastSeenAt":"2026-04-22T06:51:58.277Z","tsv":"'/api/posts':460 '/api/users':279 '/postslist':710 '0':831 '1':251,521,657 '1000':316,656,817 '2':264,583 '3':292,605,971 '5':318,323 '60':317,655,818 'abstract':230,867 'across':808 'activ':262 'advanc':337 'aggress':662 'alway':229,606 'app':25,155,378,621 'app/posts/page.tsx':698 'app/posts/postslist.tsx':749 'app/providers.tsx':628 'applic':58 'application/json':467 'array':104,308,349,905 'array-bas':103,307 'ask':1063 'async':271,452,529,715 'asynchron':11,50,178 'automat':968 'avail':216 'await':277,458,543,728 'back':505,596 'background':69,184,326,482,838,1000 'base':105,309 'basic':413 'behavior':121 'best':227,793 'better':853 'bodi':468 'boundari':72,160,1071 'box':200 'build':47 'cach':64,134,183,345,411,429,478,498,736,778 'cachetim':993 'call':232,527,872 'callback':887 'cancel':531 'chang':824 'check':944,983 'children':644,645,671 'clarif':1065 'clear':1038 'client':159,428,630,669,690,711,750,753 'closur':898 'compon':158,673,700,712,751,842,1016 'concept':163 'configur':19,111 'confus':994 'const':269,275,298,380,385,390,397,402,409,444,446,456,512,514,551,647,718,779,880 'content':465 'content-typ':464 'context':575,590,600,603 'core':162 'correct':954 'cover':14 'creat':796 'criteria':1074 'custom':224,234,295,874 'data':15,62,92,174,193,211,319,420,433,681,724,780,821,864,910,918,919,923,1010,1021 'data.map':787 'debug':987 'declar':61 'dedupl':186 'default':641,714,759,828,845,973 'defaultopt':652 'defin':252,265 'definit':221 'dehydr':702,734,746,776 'delet':1024 'depend':330,904 'deriv':928,930 'desc':362,368 'describ':1042 'design':100 'detail':398,400,403 'develop':46 'differ':809 'direct':889,924 'doesn':822 'drill':694 'e.g':816,915 'enabl':328 'encapsul':237 'ensur':613 'environ':1054 'environment-specif':1053 'err':598 'error':71,285,609 'even':1027 'everi':825,841 'except':959 'exist':336 'expert':4,5,31,43,1059 'export':293,297,379,443,511,640,713,758 'factori':369,799 'fail':286,509,587 'fals':660,985 'feedback':147,494 'fetch':16,63,93,173,210,239,278,288,459,676,680,937,949 'fetcher':267 'fetchissu':364 'fetchpostsclientsid':785 'fetchpostsserversid':733 'fetchus':270,313 'file':810 'filter':354,392,395 'former':40,992 'fresh':321,863 'function':268,642,716,760 'gctime':118,991,1004,1019 'get':1028 'give':490 'global':112,814 'govern':997,1005 'grade':37 'handl':182 'header':463 'help':45 'high':374 'hit':961 'hook':126,225,235,296,875 'hydrat':79,161,677 'hydrationboundari':703,742,744 'id':257,404,407 'identifi':343 'immedi':523 'implement':141 'import':247,438,631,636,701,707,754 'inact':263,1009 'infinit':936,982 'initi':624 'initialdata':696 'inlin':888 'input':1068 'instant':145,493,773 'instead':899 'integr':28,150,623 'invalid':65,132,412,416,475 'invalidatequeri':856 'isn':951 'issu':358,383 'issuekey':381 'issuekeys.all':387,399 'issuekeys.details':406 'issuekeys.lists':394 'json.stringify':469 'key':102,108,245,311,339,341,373,790,798 'larg':377 'layer':53 'let':858 'limit':1030 'list':386,388,391 'loading/error':201 'local':912 'logic':94,240,950 'long':1007 'loop':938,981 'manag':13,52,180 'master':60 'match':1039 'matter':352 'mean':832 'memoiz':893 'memori':1013 'method':461 'minut':324,658 'miss':1076 'misspel':804 'modifi':419 'mount':770 'multipl':188 'must':347,425 'mutat':20,138,410,414,525,586,881 'mutationfn':451,519 'name':259 'need':927 'network':767,941 'never':206 'new':284,559,650,720 'newpost':453,470 'newtodo':530,571,599 'newtodo.id':569 'next.js':24,57,154,620 'number':405 'object':576 'old':432,563 'old.map':565 'onerror':597 'onmut':528,593 'onsettl':616 'onsuccess':484 'open':360,366 'optimist':21,66,142,488,541,555 'order':351 'organ':865 'out-of-the-box':196 'outgo':533 'output':1048 'overwrit':539 'p':789 'pagin':194 'pass':686,738,885 'pattern':80,222,226,370 'perform':49 'permiss':1069 'post':462,477,487,731,783,788 'post.id':791 'post.title':792 'post/put/delete':128 'postslist':708,761 'postspag':717 'practic':228,794 'pre':675,679 'pre-fetch':674,678 'prefetch':722 'prevent':661 'previous':549 'previoustodo':552,582,604 'primit':886 'problem':935,988 'product':36 'production-grad':35 'promis':274 'prop':693 'prop-dril':692 'provid':626,643 'queri':3,8,10,30,39,42,101,115,152,166,168,214,220,244,310,331,338,340,372,653,797,834,860,909,922,965 'query-specif':114 'querycli':447,515,632,648,651,670,704,719,721,747 'queryclient.cancelqueries':544 'queryclient.getquerydata':553 'queryclient.invalidatequeries':135,485,617 'queryclient.prefetchquery':729 'queryclient.setquerydata':561,601,848 'queryclientprovid':633,668 'queryfn':312,363,732,784,946 'querykey':304,357,486,545,618,730,782,903 'react':9,41,55,639,913 'react.reactnode':646 'read':772 'recommend':375 'refactor':91 'refetch':327,483,534,607,663,839,861,1001 'refetchonwindowfocus':659 'reli':896,900 'remount':843 'render':77,933 'replac':95 'request':129,189,508,768 'requir':1067 'res':276,457 'res.json':291,472 'res.ok':282 'respond':502 'retri':120,967,984 'return':290,302,449,471,517,573,581,591,667,743,786,963 'review':1060 'robust':48 'roll':504,595 'router':26,156,622 'rule':203 'run':333 'safeti':1070 'say':879 'scope':1041 'second':826 'server':75,157,423,501,614,672,684,699,727,777 'server-sid':74 'set':88,812 'setlocalst':917 'side':76 'skill':85,1033 'skill-tanstack-query-expert' 'snapshot':547,579 'solut':943,995 'sort':355,361,367 'source-sickn33' 'spare':849 'specif':116,1055 'ssr':27,78 'stack':219 'stale':17,436,1029 'staletim':117,315,654,815,829,989,996,1020 'state':12,51,179,202,745,914,929 'status':261,359,365 'stay':1011 'stop':1061 'strict':106,253 'string':258,260,273,301,393,455 'structur':953 'substitut':1051 'success':474,611,1073 'switch':666 'sync':70,615,908 'tab':665,942 'tanstack':2,7,29,38,151,165,167,213,833,859,964 'tanstack-query-expert':1 'tanstack/react-query':250,442,635,706,757 'task':1037 'tell':426 'test':1057 'throw':283,956 'thumb':205 'time':18,972 'titl':454 'todo':546,554,562,566,570,572,602,619 'todo.id':568 'topic-agent-skills' 'topic-agentic-skills' 'topic-ai-agent-skills' 'topic-ai-agents' 'topic-ai-coding' 'topic-ai-workflows' 'topic-antigravity' 'topic-antigravity-skills' 'topic-claude-code' 'topic-claude-code-skills' 'topic-codex-cli' 'topic-codex-skills' 'treat':1046 'trigger':480,522,765,836,1003 'troubleshoot':934 'type':107,242,254,255,466 'typescript':241,246,353,437,510,627,697,748 'ui':67 'unhandl':958 'uniqu':342 'unmount':1017 'unstabl':978 'updat':22,68,143,185,489,496,542,556 'updatetodofn':520 'use':83,86,98,109,122,130,139,148,207,588,629,752,847,920,1031 'usecreatepost':445,882 'useeffect':96,208,916,979 'usemut':125,439,450,518,869 'usequeri':231,248,303,356,755,781,871,891 'usequerycli':440,448,516 'user':256,289,305,492,805,807 'userid':272,280,300,306,314,329,335 'usest':97,637,649 'useupdatetodo':513 'useus':299 'usual':852 'ux':146 'valid':1056 'valu':550,560,580 'view':876 'vs':806,990 'without':691,892 'wrap':975 'write':124","prices":[{"id":"ec2ae777-29aa-454e-86d1-1f2708872c05","listingId":"a682398b-1cdc-4399-907b-8927be3dacd4","amountUsd":"0","unit":"free","nativeCurrency":null,"nativeAmount":null,"chain":null,"payTo":null,"paymentMethod":"skill-free","isPrimary":true,"details":{"org":"sickn33","category":"antigravity-awesome-skills","install_from":"skills.sh"},"createdAt":"2026-04-18T21:45:50.025Z"}],"sources":[{"listingId":"a682398b-1cdc-4399-907b-8927be3dacd4","source":"github","sourceId":"sickn33/antigravity-awesome-skills/tanstack-query-expert","sourceUrl":"https://github.com/sickn33/antigravity-awesome-skills/tree/main/skills/tanstack-query-expert","isPrimary":false,"firstSeenAt":"2026-04-18T21:45:50.025Z","lastSeenAt":"2026-04-22T06:51:58.277Z"}],"details":{"listingId":"a682398b-1cdc-4399-907b-8927be3dacd4","quickStartSnippet":null,"exampleRequest":null,"exampleResponse":null,"schema":null,"openapiUrl":null,"agentsTxtUrl":null,"citations":[],"useCases":[],"bestFor":[],"notFor":[],"kindDetails":{"org":"sickn33","slug":"tanstack-query-expert","github":{"repo":"sickn33/antigravity-awesome-skills","stars":34460,"topics":["agent-skills","agentic-skills","ai-agent-skills","ai-agents","ai-coding","ai-workflows","antigravity","antigravity-skills","claude-code","claude-code-skills","codex-cli","codex-skills","cursor","cursor-skills","developer-tools","gemini-cli","gemini-skills","kiro","mcp","skill-library"],"license":"mit","html_url":"https://github.com/sickn33/antigravity-awesome-skills","pushed_at":"2026-04-22T06:40:00Z","description":"Installable GitHub library of 1,400+ agentic skills for Claude Code, Cursor, Codex CLI, Gemini CLI, Antigravity, and more. Includes installer CLI, bundles, workflows, and official/community skill collections.","skill_md_sha":"6e4ff9310e7b06add5e7f492be3becac9b43e75a","skill_md_path":"skills/tanstack-query-expert/SKILL.md","default_branch":"main","skill_tree_url":"https://github.com/sickn33/antigravity-awesome-skills/tree/main/skills/tanstack-query-expert"},"layout":"multi","source":"github","category":"antigravity-awesome-skills","frontmatter":{"name":"tanstack-query-expert","description":"Expert in TanStack Query (React Query) — asynchronous state management. Covers data fetching, stale time configuration, mutations, optimistic updates, and Next.js App Router (SSR) integration."},"skills_sh_url":"https://skills.sh/sickn33/antigravity-awesome-skills/tanstack-query-expert"},"updatedAt":"2026-04-22T06:51:58.277Z"}}