본문으로 건너뛰기
Skillpedia
웹사이트 및 UI (프런트엔드)48k · #5927

tanstack-query-expert

하는 일

이 전문가는 React와 Next.js로 만든 웹 애플리케이션의 데이터를 관리하도록 돕습니다. 데이터를 가져오고, 업데이트하고, 표시하는 방식을 정리해 애플리케이션을 더 빠르고 안정적으로 만듭니다.

사용하는 경우

  • ✓React/Next.js 애플리케이션에서 데이터 가져오기를 시작할 때.
  • ✓전체 페이지를 다시 불러오지 않고 데이터를 업데이트해서 사용자 인터페이스가 더 빠르게 느껴지기를 원할 때.
  • ✓서버와 브라우저에서 원활하게 작동하도록 데이터 가져오기를 Next.js와 통합하는 경우.

스킬 링크

https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/tanstack-query-expert/SKILL.md

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/tanstack-query-expert/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“TanStack Query를 설정해서 사용자 데이터를 가져오고 화면에 표시하려면 어떻게 해야 하나요?”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

데이터 가져오기를 정리하기 위해 '커스텀 훅'이라는 패턴을 사용하는 방법을 가르칩니다. 여기에는 데이터를 어떻게 가져올지, 어떻게 식별할지, 업데이트와 오류를 어떻게 처리할지 정의하는 것이 포함됩니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.

TanStack Query Expert

You 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.

When to Use This Skill

  • Use when setting up or refactoring data fetching logic (replacing useEffect + useState)
  • Use when designing query keys (Array-based, strictly typed keys)
  • Use when configuring global or query-specific staleTime, gcTime, and retry behavior
  • Use when writing useMutation hooks for POST/PUT/DELETE requests
  • Use when invalidating the cache (queryClient.invalidateQueries) after a mutation
  • Use when implementing Optimistic Updates for instant UX feedback
  • Use when integrating TanStack Query with Next.js App Router (Server Components + Client Boundary hydration)

Core Concepts

Why TanStack Query?

TanStack 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.

Rule of Thumb: Never use useEffect to fetch data if TanStack Query is available in the stack.

Query Definition Patterns

The Custom Hook Pattern (Best Practice)

Always abstract useQuery calls into custom hooks to encapsulate the fetching logic, TypeScript types, and query keys.

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

// 1. Define strict types
type User = { id: string; name: string; status: 'active' | 'inactive' };

// 2. Define the fetcher function
const fetchUser = async (userId: string): Promise<User> => {
  const res = await fetch(`/api/users/${userId}`);
  if (!res.ok) throw new Error('Failed to fetch user');
  return res.json();
};

// 3. Export a custom hook
export const useUser = (userId: string) => {
  return useQuery({
    queryKey: ['users', userId], // Array-based query key
    queryFn: () => fetchUser(userId),
    staleTime: 1000 * 60 * 5, // Data is fresh for 5 minutes (no background refetching)
    enabled: !!userId, // Dependent query: only run if userId exists
  });
};

Advanced Query Keys

Query keys uniquely identify the cache. They must be arrays, and order matters.

// Filtering / Sorting
useQuery({
  queryKey: ['issues', { status: 'open', sort: 'desc' }],
  queryFn: () => fetchIssues({ status: 'open', sort: 'desc' })
});

// Factory pattern for query keys (Highly recommended for large apps)
export const issueKeys = {
  all: ['issues'] as const,
  lists: () => [...issueKeys.all, 'list'] as const,
  list: (filters: string) => [...issueKeys.lists(), { filters }] as const,
  details: () => [...issueKeys.all, 'detail'] as const,
  detail: (id: number) => [...issueKeys.details(), id] as const,
};

Mutations & Cache Invalidation

Basic Mutation with Invalidation

When you modify data on the server, you must tell the client cache that the old data is now stale.

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

export const useCreatePost = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: async (newPost: { title: string }) => {
      const res = await fetch('/api/posts', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(newPost),
      });
      return res.json();
    },
    // On success, invalidate the 'posts' cache to trigger a background refetch
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['posts'] });
    },
  });
};

Optimistic Updates

Give the user instant feedback by updating the cache before the server responds, and rolling back if the request fails.

export const useUpdateTodo = () => {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: updateTodoFn,
    
    // 1. Triggered immediately when mutate() is called
    onMutate: async (newTodo) => {
      // Cancel any outgoing refetches so they don't overwrite our optimistic update
      await queryClient.cancelQueries({ queryKey: ['todos'] });

      // Snapshot the previous value
      const previousTodos = queryClient.getQueryData(['todos']);

      // Optimistically update to the new value

…
자주 묻는 질문

TanStack Query란 무엇인가요?

웹 애플리케이션에서 시간에 따라 바뀌는 데이터를 관리하도록 돕는 도구입니다. 데이터 가져오기, 캐싱, 자동 업데이트를 처리합니다.

데이터 가져오기에 `useEffect`를 쓰지 않는 이유는 무엇인가요?

TanStack Query가 더 효율적입니다. 캐싱을 관리하고, 중복 요청을 피하며, 로딩과 오류 상태를 처리합니다. `useEffect`는 이것을 스스로 해 주지 않습니다.

'쿼리 키'란 무엇인가요?

가져온 각 데이터의 고유 식별자입니다. TanStack Query가 어떤 데이터를 가져오고, 업데이트하고, 무효화할지 알 수 있게 합니다.

상세 정보

작성자의 원본 설명

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.

repo: sickn33/agentic-awesome-skills

인기도

GitHub 스타
48k
순위
#5927
라이선스
MIT
업데이트
2026. 10. 15.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬