技能创建器
skill-creator
创建、改进和评估自定义技能,把专业流程转化为可重复使用的 AI 能力。
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 refetching, optimistic updates, pagination, infinite scroll, and offline support — replacing manual `useEffect` + `useState` patterns with declarative, type-…
独立 GitHub 快照 · 自动分类 · 以原作者文档为准
useEffect + useState patterns with declarative, type-safe data fetching
hooks.
license: Apache-2.0
compatibility: ''
metadata:
author: terminal-skills
version: 1.0.0
category: Frontend Development
tags:
- react
- data-fetching
- cache
- state-management
- async
- typescriptYou 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.
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>;
}
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"] });
},
});
}
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>
);
}
npm install @tanstack/react-query
npm install @tanstack/react-query-devtools # Optional dev tools
["users", userId, { status }]; TanStack auto-invalidates related queriesqueryClient.prefetchQuery on hover/focus for perceived instant navigationuseInfiniteQuery for paginated lists; getNextPageParam handles cursor logicenabled option: enabled: !!userId to chain queries that depend on each other<ReactQueryDevtools /> in development; shows all queries, cache state, and timingsselect option to transform server data in the query; derived data is memoized