Skip to content
Skillv1.0.0

tanstack-query

You are an expert in TanStack Query (formerly React Query), the data-fetching and server state management library. You help developers build React applications with automatic caching, background refet

by terminalskills(0) 0 installs
Free
Sign in to install

Free account. Installing gives you the manifest plus copy-paste snippets.

See reviews

About

Imported from terminalskills/skills (skills/tanstack-query/SKILL.md). Install upstream with npx skills add terminalskills/skills --skill tanstack-query. Copyright stays with the author (Apache-2.0).

TanStack Query — Async State Management for React

You are an expert in TanStack Query (formerly React Query), the data-fetching and server state management library. You help developers build React applications with automatic caching, background refetching, optimistic updates, pagination, infinite scroll, and offline support — replacing manual useEffect + useState patterns with declarative, type-safe data fetching hooks.

Core Capabilities

Basic Queries

import { useQuery, useMutation, useQueryClient, QueryClient, QueryClientProvider } from "@tanstack/react-query";

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 5 * 60 * 1000,          // 5 min before refetch
      gcTime: 10 * 60 * 1000,            // 10 min cache lifetime
      retry: 2,
      refetchOnWindowFocus: true,
    },
  },
});

// Wrap app
function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <Dashboard />
    </QueryClientProvider>
  );
}

function UserList() {
  const { data, isLoading, error } = useQuery({
    queryKey: ["users"],
    queryFn: () => fetch("/api/users").then(r => r.json()),
  });

  if (isLoading) return <Skeleton />;
  if (error) return <Error message={error.message} />;
  return <ul>{data.map(u => <li key={u.id}>{u.name}</li>)}</ul>;
}

Mutations with Optimistic Updates

function useCreateTodo() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (newTodo: { title: string }) =>
      fetch("/api/todos", { method: "POST", body: JSON.stringify(newTodo) }).then(r => r.json()),

    onMutate: async (newTodo) => {
      await queryClient.cancelQueries({ queryKey: ["todos"] });
      const previous = queryClient.getQueryData(["todos"]);
      queryClient.setQueryData(["todos"], (old: Todo[]) => [
        ...old, { id: "temp", ...newTodo, completed: false },
      ]);
      return { previous };
    },
    onError: (_err, _todo, context) => {
      queryClient.setQueryData(["todos"], context?.previous);
    },
    onSettled: () => {
      queryClient.invalidateQueries({ queryKey: ["todos"] });
    },
  });
}

Infinite Scroll

function InfiniteFeed() {
  const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = useInfiniteQuery({
    queryKey: ["feed"],
    queryFn: ({ pageParam }) => fetch(`/api/feed?cursor=${pageParam}`).then(r => r.json()),
    initialPageParam: "",
    getNextPageParam: (lastPage) => lastPage.nextCursor ?? undefined,
  });

  return (
    <div>
      {data?.pages.map(page => page.items.map(item => <FeedItem key={item.id} item={item} />))}
      <button onClick={() => fetchNextPage()} disabled={!hasNextPage || isFetchingNextPage}>
        {isFetchingNextPage ? "Loading..." : hasNextPage ? "Load more" : "No more"}
      </button>
    </div>
  );
}

Installation

npm install @tanstack/react-query
npm install @tanstack/react-query-devtools  # Optional dev tools

Best Practices

  1. Query keys — Use arrays: ["users", userId, { status }]; TanStack auto-invalidates related queries
  2. staleTime — Set based on data freshness needs; 0 = always refetch, 5min for semi-static data
  3. Optimistic updates — Update cache immediately on mutation; rollback on error for instant UX
  4. Prefetching — Use queryClient.prefetchQuery on hover/focus for perceived instant navigation
  5. Infinite queries — Use useInfiniteQuery for paginated lists; getNextPageParam handles cursor logic
  6. Dependent queries — Use enabled option: enabled: !!userId to chain queries that depend on each other
  7. DevTools — Add <ReactQueryDevtools /> in development; shows all queries, cache state, and timings
  8. Select for transforms — Use select option to transform server data in the query; derived data is memoized

Use it

Copy one of these into your project. Installing also returns the manifest and these snippets.

yaml
targets:
  - https://api.opensmartroute.ai/api/v1/registry/terminalskills-skills-tanstack-query/manifest   # or paste the manifest below

Manifest

An Open Capability Manifest: the router reads it to know what this does, what it costs and when to pick it.

terminalskills-skills-tanstack-query.ocm.jsonjson
{
  "ocm": "1",
  "id": "terminalskills-skills-tanstack-query",
  "kind": "skill",
  "name": "tanstack-query",
  "description": "You are an expert in TanStack Query (formerly React Query), the data-fetching and server state management library. You help developers build React applications with automatic caching, background refetching, optimistic updates, pagination, infinite scroll, and offline support — replacing manual `useEffect` + `useState` patterns with declarative, type-safe data fetching hooks.",
  "publisher": "terminalskills",
  "version": "1.0.0",
  "capabilities": {
    "domains": [
      "data_analysis"
    ],
    "tags": [
      "skill-md",
      "react",
      "data-fetching",
      "cache",
      "state-management",
      "async",
      "typescript",
      "skills-sh"
    ],
    "languages": [
      "en"
    ]
  },
  "quality_prior": 0.6,
  "examples": [
    "You are an expert in TanStack Query (formerly React Query), the data-fetching and server state management library. You help developers build React applications with automatic caching, background refetching, optimistic updates, pagination, infinite scroll, and offline support — replacing manual `useEffect` + `useState` patterns with declarative, type-safe data fetching hooks."
  ],
  "primary": false,
  "metadata": {
    "source": {
      "provider": "skills.sh",
      "repository": "https://github.com/terminalskills/skills",
      "path": "skills/tanstack-query/SKILL.md",
      "ref": "HEAD",
      "url": "https://github.com/terminalskills/skills/blob/HEAD/skills/tanstack-query/SKILL.md",
      "key": "terminalskills/skills/skills/tanstack-query/SKILL.md"
    },
    "license": "Apache-2.0"
  },
  "instructions": "# TanStack Query — Async State Management for React\n\nYou are an expert in TanStack Query (formerly React Query), the data-fetching and server state management library. You help developers build React applications with automatic caching, background refetching, optimistic updates, pagination, infinite scroll, and offline support — replacing manual `useEffect` + `useState` patterns with declarative, type-safe data fetching hooks.\n\n## Core Capabilities\n\n### Basic Queries\n\n```tsx\nimport { useQuery, useMutation, useQueryClient, QueryClient, QueryClientProvider } from \"@tanstack/react-query\";\n\nconst ",
  "cost": {
    "context_tokens": 962
  }
}

Fetch it by URL: GET /api/v1/registry/terminalskills-skills-tanstack-query/manifest?version=1.0.0

Reviews

Star ratings from people who tried it. One review per account; edit yours any time.

No reviews yet. Install it, try it, and be the first to rate it.