AgentSkillsCN

tanstack-query

针对 React 应用程序,掌握查询模式、缓存机制、变更操作以及服务器端状态管理。适用于实现数据获取钩子或复杂状态逻辑时使用此技能。

SKILL.md
--- frontmatter
name: tanstack-query
description: Query patterns, caching, mutations, and server-state management for React applications. Use this skill when implementing data fetching hooks or complex state logic.

TanStack Query (React Query)

Best practices for managing server state in React applications using TanStack Query v5.

Core Concepts

  • QueryClient: The central cache manager.
  • useQuery: Fetching data with automatic caching and background updates.
  • useMutation: Performing side effects (POST/PUT/DELETE) and updating the cache.
  • Query Keys: Structured keys (e.g., ['users', id]) for precise cache control.

Best Practices

  • Invalidation: Always use queryClient.invalidateQueries after mutations to keep data fresh.
  • Error Handling: Use onError or global error boundaries for consistent UX.
  • Optimistic Updates: Implement UI changes before server confirmation for a "snappy" feel.
  • Prefetching: Load data before the user needs it (e.g., on hover).

When to Apply

  • Creating new data hooks.
  • Handling paginated or infinite loading lists.
  • Managing complex form submissions with server feedback.
  • Optimizing network performance via caching.