tanstack-query
하는 일
이 스킬은 TanStack Query 버전 5로 서버 데이터를 가져오고 캐싱하는 과정을 에이전트에게 안내합니다. 온라인 서비스에서 데이터를 불러오는 React 앱을 만드는 개발자를 위한 스킬입니다.
사용하는 경우
- ✓React 컴포넌트가 API에서 데이터를 가져와야 할 때.
- ✓로딩과 캐싱을 일관된 방식으로 처리하고 싶을 때.
- ✓어떤 동작이 데이터를 바꿔서 화면을 그에 맞게 새로 고쳐야 할 때.
스킬 링크
https://github.com/Kiranism/next-shadcn-dashboard-starter/blob/main/.agents/skills/tanstack-query/SKILL.md복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.
사용 방법
가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.
바로 붙여넣을 수 있는 메시지
Claude Code, Codex, Cursor용입니다. 프로젝트 폴더에서 실행하면 스킬이 설치됩니다.
SKILL.md를 다운로드해 에이전트의 스킬 폴더에 넣으세요.
AI에게 요청하는 예시
“React 앱에서 주문 목록을 가져오고, 새 주문이 추가된 뒤 목록을 새로 고쳐 주세요.”
매주 새 스킬 5개. 읽는 데 1분.
작동 방식
에이전트는 쿼리 훅과 중앙 API 서비스 파일을 사용하며, 변경 후 캐시된 데이터를 새로 고치거나 업데이트합니다. 버전 5의 이름과 규칙을 따릅니다.
기술 내용 (원본 SKILL.md)
작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.
TanStack Query Patterns
Purpose
Modern data fetching with TanStack Query v5 (latest: 5.90.5, November 2025), emphasizing Suspense-based queries, cache-first strategies, and centralized API services.
Note: v5 (released October 2023) has breaking changes from v4:
isLoading→isPendingfor statuscacheTime→gcTime(garbage collection time)- React 18.0+ required
- Callbacks removed from useQuery (onError, onSuccess, onSettled)
keepPreviousDatareplaced withplaceholderDatafunction
When to Use This Skill
- Fetching data with TanStack Query
- Using useSuspenseQuery or useQuery
- Managing mutations
- Cache invalidation and updates
- API service patterns
Quick Start
Primary Pattern: useSuspenseQuery
For all new components, use useSuspenseQuery:
import { useSuspenseQuery } from '@tanstack/react-query';
import { postsApi } from '~/features/posts/api/postsApi';
function PostList() {
const { data: posts } = useSuspenseQuery({
queryKey: ['posts'],
queryFn: postsApi.getAll,
});
return (
<div>
{posts.map(post => (
<PostCard key={post.id} post={post} />
))}
</div>
);
}
// Wrap with Suspense
<Suspense fallback={<PostsSkeleton />}>
<PostList />
</Suspense>
Benefits:
- No
isLoadingchecks needed - Integrates with Suspense boundaries
- Cleaner component code
- Consistent loading UX
useSuspenseQuery Patterns
Basic Usage
const { data } = useSuspenseQuery({
queryKey: ['user', userId],
queryFn: () => userApi.get(userId),
});
// data is never undefined - guaranteed by Suspense
return <div>{data.name}</div>;
With Parameters
function UserPosts({ userId }: { userId: string }) {
const { data: posts } = useSuspenseQuery({
queryKey: ['users', userId, 'posts'],
queryFn: () => postsApi.getByUser(userId),
});
return <div>{posts.length} posts</div>;
}
Dependent Queries
function PostDetails({ postId }: { postId: string }) {
// First query
const { data: post } = useSuspenseQuery({
queryKey: ['posts', postId],
queryFn: () => postsApi.get(postId),
});
// Second query depends on first
const { data: author } = useSuspenseQuery({
queryKey: ['users', post.authorId],
queryFn: () => userApi.get(post.authorId),
});
return <div>{author.name} wrote {post.title}</div>;
}
useQuery (Legacy Pattern)
Use useQuery only when you need loading/error states in the component:
import { useQuery } from '@tanstack/react-query';
function Component() {
const { data, isPending, error } = useQuery({
queryKey: ['posts'],
queryFn: postsApi.getAll,
});
if (isPending) return <Spinner />;
if (error) return <Error error={error} />;
return <div>{data.map(...)}</div>;
}
When to use useQuery vs useSuspenseQuery:
- Use
useSuspenseQueryby default (preferred) - Use
useQueryonly when you need component-level loading states - Most cases should use
useSuspenseQuery+ Suspense boundaries
Mutations
Basic Mutation
import { useMutation, useQueryClient } from '@tanstack/react-query';
function CreatePostButton() {
const queryClient = useQueryClient();
const mutation = useMutation({
mutationFn: postsApi.create,
onSuccess: () => {
// Invalidate and refetch
queryClient.invalidateQueries({ queryKey: ['posts'] });
},
});
const handleCreate = () => {
mutation.mutate({
title: 'New Post',
content: 'Content here',
});
};
return (
<button onClick={handleCreate} disabled={mutation.isPending}>
{mutation.isPending ? 'Creating...' : 'Create Post'}
</button>
);
}
Optimistic Updates
const mutation = useMutation({
mutationFn: postsApi.update,
onMutate: async (updatedPost) => {
// Cancel outgoing refetches
await queryClient.cancelQueries({ queryKey: ['posts', updatedPost.id] });
// Snapshot previous value
const previousPost = queryClient.getQueryData(['posts', updatedPost.id]);
// Optimistically update
queryClient.setQueryData(['posts', updatedPost.id], updatedPost);
// Return context with snapshot
return { previousPost };
},
onError: (err, updatedPost, context) => {
// Rollback on error
queryClient.setQueryData(['posts', updatedPost.id], context.previousPost);
},
onSettled: (data, error, variables) => {
자주 묻는 질문
버전 5에서 무엇이 바뀌었나요?
isLoading이 isPending으로 바뀌는 등 일부 이름이 바뀌었고, 쿼리의 일부 콜백이 제거되었습니다.
Suspense 로딩이란 무엇인가요?
데이터가 불러와지는 동안 대체 화면을 보여 주므로, 컴포넌트마다 별도의 로딩 검사를 할 필요가 없습니다.
API 호출은 어디에 두어야 하나요?
스킬은 쿼리 훅이 호출하는 중앙 API 서비스 파일을 두라고 권장합니다.
상세 정보
작성자의 원본 설명
TanStack Query v5 data fetching patterns including useSuspenseQuery, useQuery, mutations, cache management, and API service integration. Use when fetching data, managing server state, or working with TanStack Query hooks.
인기도
- GitHub 스타
- 7.2k
- 순위
- #13312
- 라이선스
- MIT
- 업데이트
- 2026. 11. 1.
댓글
- …
이 저장소의 다른 스킬
kiranism-shadcn-dashboard
7.2k에이전트가 Next.js 관리자 대시보드에 페이지, 표, 양식, 내비게이션, 테마를 추가하고 템플릿 고유의 패턴을 따르도록 돕습니다.
next-best-practices
7.2k에이전트가 라우트, 서버 컴포넌트, 데이터 로딩, 오류 페이지에 대한 최신 모범 사례를 따라 Next.js 코드를 작성하고 검토하도록 돕습니다.
tanstack-form
7.2k에이전트가 React와 다른 프레임워크에서 필드 검사, 반복 필드, 스키마 검증을 갖춘 타입 안전한 폼을 만들도록 돕습니다.
비슷한 스킬
angular-developer
280k에이전트가 Angular 코드를 만들고 프로젝트 구조를 조언하도록 돕습니다. 새 프로젝트 시작, 코드 부분 생성, 성능과 접근성 개선에 유용합니다.
frontend-a11y
280k모든 사람이 웹 인터페이스를 쓸 수 있도록 에이전트를 돕습니다. 웹사이트와 앱이 화면 읽기 프로그램과 키보드 탐색에서 잘 작동하도록 합니다.
frontend-patterns
280k프론트엔드 개발의 현대적인 패턴을 적용하도록 에이전트를 돕습니다. React와 Next.js에서 성능을 최적화하고, 상태를 관리하며, 모범 사례를 따릅니다.