Command Palette

Search for a command to run...

UnylyUnyly
Назад к скиллам

tanstack-query

БесплатноБез исполняемых скриптовНе проверен

TanStack Query (formerly React Query) fetches, caches and updates server data in React apps, replacing hand-written useEffect + useState fetching. Use it when…

TerminalSkillsот TerminalSkills★ 221 звезда на GitHub

Об этом скилле

TanStack Query

Overview

TanStack Query (v5, package @tanstack/react-query) manages server state: it caches responses by query key, dedupes requests, refetches in the background and gives mutations a lifecycle for optimistic UI. It needs React 18 or newer. These examples use the v5 object-only API; v4 names (cacheTime, isLoading as "no data yet", keepPreviousData, onSuccess on useQuery) no longer exist.

Instructions

Setup

npm install @tanstack/react-query
npm install -D @tanstack/react-query-devtools
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { ReactQueryDevtools } from "@tanstack/react-query-devtools";

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 60_000,   // fresh for 1 min; default is 0 (always stale)
      gcTime: 10 * 60_000, // unused cache kept 10 min; default is 5 min
    },
  },
});

export function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <Dashboard />
      <ReactQueryDevtools initialIsOpen={false} />
    </QueryClientProvider>
  );
}

Devtools are left out of production builds automatically.

Queries

fetch does not reject on HTTP 4xx/5xx, so throw yourself or the query ends up "successful" with an error body.

import { useQuery } from "@tanstack/react-query";

type User = { id: number; name: string };

async function fetchUsers(): Promise<User[]> {
  const res = await fetch("/api/users");
  if (!res.ok) throw new Error(`Users request failed: ${res.status}`);
  return res.json();
}

function UserList() {
  const { data, isPending, isError, error } = useQuery({
    queryKey: ["users"],
    queryFn: fetchUsers,
  });

  if (isPending) return <p>Loading...</p>;
  if (isError) return <p>{error.message}</p>; // error is Error by default in v5
  return <ul>{data.map((u) => <li key={u.id}>{u.name}</li>)}</ul>;
}

In v5, isPending means "no data yet"; isLoading is isPending && isFetching (first fetch in flight). Only isPending narrows data to defined.

Share key and function with queryOptions so useQuery, useSuspenseQuery, prefetchQuery and setQueryData stay in sync and typed:

import { queryOptions, useQuery } from "@tanstack/react-query";

export const userQuery = (id: number) =>
  queryOptions({
    queryKey: ["users", id],
    queryFn: () => fetch(`/api/users/${id}`).then((r) => r.json() as Promise<User>),
    staleTime: 30_000,
  });

const { data } = useQuery({ ...userQuery(7), select: (u) => u.name });

Dependent query: useQuery({ ...projectsQuery(userId!), enabled: userId != null }).

Mutations and optimistic updates

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

type Todo = { id: number | string; title: string; completed: boolean };

export function useCreateTodo() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (newTodo: { title: string }) => {
      const res = await fetch("/api/todos", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(newTodo),
      });
      if (!res.ok) throw new Error(`Create failed: ${res.status}`);
      return (await res.json()) as Todo;
    },
    onMutate: async (newTodo) => {
      await queryClient.cancelQueries({ queryKey: ["todos"] });
      const previous = queryClient.getQueryData<Todo[]>(["todos"]);
      queryClient.setQueryData<Todo[]>(["todos"], (old = []) => [
        ...old,
        { id: `temp-${Date.now()}`, completed: false, ...newTodo },
      ]);
      return { previous };
    },
    onError: (_err, _vars, context) => {
      queryClient.setQueryData(["todos"], context?.previous);
    },
    // return the promise so the mutation stays pending until the refetch ends
    onSettled: () => queryClient.invalidateQueries({ queryKey: ["todos"] }),
  });
}

Simpler alternative with no cache writes: render mutation.variables as a greyed item while mutation.isPending; it disappears on its own after the refetch. From another component use useMutationState with a mutationKey.

Infinite queries

initialPageParam is required in v5. maxPages only works together with both getNextPageParam and getPreviousPageParam. Returning undefined or null from getNextPageParam means there is no next page.

import { useInfiniteQuery } from "@tanstack/react-query";

type FeedPage = { items: { id: number; text: string }[]; nextCursor: string | null; prevCursor: string | null };

function InfiniteFeed() {
  const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = useInfiniteQuery({
    queryKey: ["feed"],
    queryFn: async ({ pageParam }): Promise<FeedPage> => {
      const res = await fetch(`/api/feed?cursor=${encodeURIComponent(pageParam)}`);
      if (!res.ok) throw new Error(`Feed failed: ${res.status}`);
      return res.json();
    },
    initialPageParam: "",
    getNextPageParam: (la
Полный SKILL.md на GitHub

Установить tanstack-query в Claude Code и Claude Desktop

Зарегайся, чтобы установить скилл

Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.

  • Открой команду установки в одну строку
  • Сохраняй скиллы в синхронизируемую библиотеку
  • Уведомления, когда скиллы обновляются
Зарегаться бесплатноУ меня уже есть аккаунт

Разрешённые инструменты

Инструменты, которые скиллу разрешено вызывать.

Без ограничений — скилл может использовать любой инструмент.

Вложенные файлы

_scores.json

FAQ

Что делает скилл tanstack-query?

TanStack Query (formerly React Query) fetches, caches and updates server data in React apps, replacing hand-written useEffect + useState fetching. Use it when the user wants caching, background refetching, mutations with optimistic updates, infinite scroll, Suspense or Next.js server prefetching with v5 hooks such as useQuery, useMutation and useInfiniteQuery.

Как установить скилл tanstack-query?

Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.

Скилл tanstack-query запускает скрипты?

Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.

Похожие скиллы

Сравнить tanstack-query с