Chuyển đến nội dung
Skillpedia
Website và giao diện (frontend)48k · #5927

tanstack-query-expert

Skill này làm gì

Chuyên gia này giúp lập trình viên quản lý dữ liệu trong ứng dụng web xây dựng bằng React và Next.js. Nó tổ chức cách dữ liệu được lấy về, cập nhật và hiển thị, giúp ứng dụng nhanh hơn và ổn định hơn.

Khi nào nên dùng

  • ✓Khi bắt đầu lấy dữ liệu trong ứng dụng React/Next.js.
  • ✓Khi bạn muốn giao diện cảm giác nhanh hơn nhờ cập nhật dữ liệu mà không tải lại toàn trang.
  • ✓Khi tích hợp việc lấy dữ liệu với Next.js để hoạt động liền mạch giữa máy chủ và trình duyệt.

Liên kết skill

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

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/sickn33/agentic-awesome-skills/blob/main/plugins/agentic-awesome-skills-claude/skills/tanstack-query-expert/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Làm sao để thiết lập TanStack Query để lấy dữ liệu người dùng và hiển thị trên màn hình?”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Chuyên gia hướng dẫn cách dùng một mẫu gọi là “custom hook” để tổ chức việc lấy dữ liệu. Điều này bao gồm cách định nghĩa việc lấy dữ liệu, cách nhận diện nó, và cách xử lý cập nhật và lỗi.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

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

…
Câu hỏi thường gặp

TanStack Query là gì?

Đây là công cụ giúp quản lý dữ liệu thay đổi theo thời gian trong ứng dụng web, bao gồm lấy dữ liệu, lưu cache và cập nhật tự động.

Vì sao không dùng `useEffect` để lấy dữ liệu?

TanStack Query hiệu quả hơn. Nó quản lý cache, tránh yêu cầu trùng lặp và xử lý trạng thái đang tải hoặc lỗi, điều mà `useEffect` không tự làm được.

“Query keys” là gì?

Đây là các mã nhận diện duy nhất cho từng dữ liệu bạn lấy về. Chúng giúp TanStack Query biết dữ liệu nào cần lấy, cập nhật hoặc làm mới.

Chi tiết

Mô tả gốc của tác giả

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

Độ phổ biến

Sao GitHub
48k
Vị trí xếp hạng
#5927
Giấy phép
MIT
Cập nhật
15/10/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự