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

tanstack-query

Skill này làm gì

Skill này hướng dẫn agent lấy và lưu cache dữ liệu từ server bằng TanStack Query phiên bản 5. Nó dành cho lập trình viên làm ứng dụng React tải dữ liệu từ một dịch vụ trực tuyến.

Khi nào nên dùng

  • ✓Khi một component React cần lấy dữ liệu từ API.
  • ✓Khi bạn muốn việc tải và lưu cache được xử lý theo cách nhất quán.
  • ✓Khi một hành động làm thay đổi dữ liệu và màn hình phải làm mới để khớp.

Liên kết skill

https://github.com/Kiranism/next-shadcn-dashboard-starter/blob/main/.agents/skills/tanstack-query/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/Kiranism/next-shadcn-dashboard-starter/blob/main/.agents/skills/tanstack-query/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ấy danh sách đơn hàng trong ứng dụng React của tôi, và làm mới danh sách sau khi có đơn hàng mới.”

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

Cách hoạt động

Agent dùng các hook truy vấn và một file dịch vụ API tập trung, rồi làm mới hoặc cập nhật dữ liệu đã lưu cache sau mỗi thay đổi. Nó tuân theo tên gọi và quy tắc của phiên bản 5.

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 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 → isPending for status
  • cacheTime → gcTime (garbage collection time)
  • React 18.0+ required
  • Callbacks removed from useQuery (onError, onSuccess, onSettled)
  • keepPreviousData replaced with placeholderData function

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 isLoading checks 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 useSuspenseQuery by default (preferred)
  • Use useQuery only 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) => {
  
Câu hỏi thường gặp

Có gì thay đổi ở phiên bản 5?

Một số tên đã đổi, như isLoading thành isPending, và một số callback đã bị bỏ khỏi query.

Tải theo suspense là gì?

Đó là cách hiển thị một nội dung dự phòng trong lúc dữ liệu tải, nên các component không cần tự kiểm tra trạng thái tải.

Các lệnh gọi API nên đặt ở đâu?

Skill khuyên nên đặt chúng trong một file dịch vụ API tập trung, và các hook truy vấn sẽ gọi đến file đó.

Chi tiết

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

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.

repo: Kiranism/next-shadcn-dashboard-starter

Độ phổ biến

Sao GitHub
7.2k
Vị trí xếp hạng
#13312
Giấy phép
MIT
Cập nhật
1/11/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ự