Token导航 LogoToken导航

Agent Skill · 开发

react-data-fetching(React 数据 fetching)

用于辅助前端页面、组件、样式和交互逻辑的开发与维护。它适合让 Agent 生成或审查 React、Next.js、Vue、Tailwind、CSS 等相关代码,整理组件结构,或定位布局和性能问题。使用时需要结合项目现有设计系统、路由和构建方式,避免只生成孤立片段;涉及页面改动时,应配合本地预览和构建检查确认视觉效果。

react-data-fetching 是开发类 Agent Skill,可用宿主为 Codex、Claude、Cursor、Gemini CLI,通过GitHub 仓库获取,权限为需要联网;许可证信息还不明确,第三方扫描已通过,按安装量在开发类的 21,746 个 Skill 里排第 4,478。

总安装 8,160周安装 340GitHub Stars 173下载 2,720核验 2026-05-01

安装说明

本站只整理中文说明,不托管安装包,也不代用户安装。
GitHub
许可证
unknown

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:react-data-fetching(React 数据 fetching)
来源仓库:https://github.com/patternsdev/skills
仓库路径:skills/react-data-fetching
安装命令:
npx skills add https://github.com/patternsdev/skills --skill react-data-fetching
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/patternsdev/skills --skill react-data-fetching

这个 Skill 是做什么的

开发类 Skill 面向写代码、改代码和排查问题,一般会读写仓库文件,部分还会执行构建或测试命令。

指导 React 应用中数据获取与缓存策略。支持 SWR、React Query 等主流方案。适用于服务端与客户端混合渲染场景。需考虑错误回退与加载状态展示。适用宿主包括 Codex、Claude、Cursor、Gemini CLI,接入前应确认版本、权限和运行环境要求。缓存失效策略影响数据实时性。

react-data-fetching 属于开发类 Skill,可作为该场景下的辅助能力补充。

来源仓库内路径:skills/react-data-fetching

上手步骤

4 步
  1. 1

    确认自己的宿主工具

    公开资料标注支持 Codex、Claude、Cursor、Gemini CLI;先确认自己用的是其中之一,再按对应工具的 Skills 目录放置。

  2. 2

    拿到安装命令

    可以直接复制的命令是 npx skills add https://github.com/patternsdev/skills --skill react-data-fetching;命令里的占位符换成自己的路径或密钥再执行。

  3. 3

    安装后重启宿主

    命令执行完要完全退出宿主工具再打开,让新装的 Skill 被重新扫描到,否则列表里可能看不到。

  4. 4

    按最小权限试用

    它需要需要联网,先在测试目录或测试账号里跑,确认没问题再放到正式项目。

常见问题

6 条

react-data-fetching 怎么安装?

在终端执行 npx skills add https://github.com/patternsdev/skills --skill react-data-fetching。装完完全退出宿主工具再打开,让它重新扫描本地 Skill。

react-data-fetching 支持哪些 AI 工具?

公开资料标注支持 Codex、Claude、Cursor、Gemini CLI。其他工具只要能读取本地 Skill 目录,一般也能手动放进去,但要自己确认触发方式是否一致。

react-data-fetching 需要什么权限?

权限级别是需要联网。该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

react-data-fetching 是免费的吗?

公开资料没有标注明确许可证,收费和商用限制都无法确认。正式使用前请到来源仓库核对授权说明。

react-data-fetching 用的人多吗?

公开数据是累计安装 8,160 次,近一周安装 340 次,下载 2,720 次,GitHub 173 星。这些数字来自第三方目录统计,只能当作热度参考,不代表质量或安全性。

react-data-fetching 安全吗?

第三方扫描结果为通过,但这只覆盖已知的静态检查项,不能替代自己读一遍源码和安装命令。

值得选的地方和要先想清楚的地方

值得选的地方

  • 同时适配 4 种工具,换客户端不用重新找替代品。
  • 第三方扫描已通过,常见的高风险行为没有命中。

先想清楚的地方

  • 许可证没有明确标注,能不能商用、能不能再分发都不确定。
  • 第三方目录整理,版本更新和行为细节以来源仓库为准。

适不适合你

更适合

  • 已经在用 Codex,想直接扩展它能力的人。
  • 需要处理开发类任务、又不想每次都手写提示词的人。

不太适合

  • 需要明确授权才能用到公司项目里的场景。
  • 需要厂商级技术支持和 SLA 的生产系统。

开发类 Skill 对比

6 个同类
Skill总安装GitHub 星权限许可证扫描
skill-vetter

技能审查员 · OpenClaw

8,779,018986操作浏览器MIT-0通过
ontology

本体论 · OpenClaw

6,636,960576只读MIT-0通过
entra-app-registration

内部应用程序注册 · Codex、Claude

6,631,872764接触敏感数据未明确通过
entra-app-registration

内部应用程序注册 · Codex、Claude

3,757,680201接触敏感数据未明确通过
nano-banana-pro

纳米香蕉专业版 · OpenClaw

3,526,898364接触敏感数据MIT-0有提醒
react-data-fetching

React 数据 fetching · 本页

8,160173需要联网未明确通过

按安装量取同分类前几名;数字来自第三方目录统计,只作热度参考,不代表质量结论。

SKILL.md 原文

React Data Fetching Patterns

Table of Contents

Production-ready patterns for fetching, caching, and synchronizing server data in React applications. These patterns are framework-agnostic — they work whether you're using Vite + React Router, Next.js, Remix, or a custom setup.

When to Use

Reference these patterns when:

  • Adding data fetching to components
  • Replacing useEffect + fetch with a proper data layer
  • Implementing caching, deduplication, or optimistic updates
  • Debugging waterfall loading patterns
  • Choosing between data fetching libraries

Instructions

  • Apply these patterns during code generation, review, and refactoring. When you see fetch-in-effect without caching or deduplication, suggest the appropriate pattern.

Details

Overview

The most common performance problem in React apps is request waterfalls — sequential fetches that could run in parallel. The second most common problem is redundant fetches — multiple components fetching the same data independently. The patterns below address both, starting with the highest-impact fixes.


1. Parallelize Independent Fetches with Promise.all

Impact: CRITICAL — Eliminates sequential waterfalls for 2-10x improvement.

When multiple fetches have no dependencies on each other, run them concurrently.

Avoid — sequential (3 round trips):

async function loadDashboard() {
  const user = await fetchUser()
  const posts = await fetchPosts()
  const notifications = await fetchNotifications()
  return { user, posts, notifications }
}

Prefer — parallel (1 round trip):

async function loadDashboard() {
  const [user, posts, notifications] = await Promise.all([
    fetchUser(),
    fetchPosts(),
    fetchNotifications(),
  ])
  return { user, posts, notifications }
}

When fetches have partial dependencies (B depends on A, but C doesn't), start independent work immediately:

async function loadPage() {
  const userPromise = fetchUser()
  const configPromise = fetchConfig()

  const user = await userPromise
  const [config, posts] = await Promise.all([
    configPromise,
    fetchPosts(user.id), // depends on user
  ])
  return { user, config, posts }
}

2. Defer Await Until the Value Is Needed

Impact: HIGH — Starts work earlier without blocking on results you don't need yet.

A common mistake is to await each promise immediately, even when subsequent code doesn't need the result right away. Start the promise early, then await it at the point where you actually read the value.

Avoid — blocks unnecessarily:

async function loadProfile(userId: string) {
  const user = await fetchUser(userId)       // waits here
  const prefs = await fetchPreferences()     // starts only after user resolves
  const avatar = buildAvatarUrl(user.avatar)
  return { user, prefs, avatar }
}

Prefer — start early, await late:

async function loadProfile(userId: string) {
  const userPromise = fetchUser(userId)      // starts immediately
  const prefsPromise = fetchPreferences()    // starts immediately

  const user = await userPromise             // await when needed
  const avatar = buildAvatarUrl(user.avatar)
  const prefs = await prefsPromise           // may already be resolved

  return { user, prefs, avatar }
}

This is complementary to Promise.all — use defer-await when you need intermediate results between fetches, and Promise.all when you can wait for everything at once.


3. Use TanStack Query for Client-Side Data

Impact: CRITICAL — Automatic caching, deduplication, revalidation, and error handling.

Raw useEffect + fetch lacks caching, deduplication, retry, and background refresh. Use a data fetching library.

Avoid — no caching, no dedup, no error handling:

function UserProfile({ userId }: { userId: string }) {
  const [user, setUser] = useState<User | null>(null)
  const [loading, setLoading] = useState(true)

  useEffect(() => {
    setLoading(true)
    fetch(`/api/users/${userId}`)
      .then(r => r.json())
      .then(setUser)
      .finally(() => setLoading(false))
  }, [userId])

  if (loading) return <Skeleton />
  return <div>{user?.name}</div>
}

Prefer — TanStack Query (recommended for Vite + React apps):

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

function UserProfile({ userId }: { userId: string }) {
  const { data: user, isLoading } = useQuery({
    queryKey: ['user', userId],
    queryFn: () => fetch(`/api/users/${userId}`).then(r => r.json()),
  })

  if (isLoading) return <Skeleton />
  return <div>{user?.name}</div>
}

TanStack Query is the strongest choice for Vite apps — it's framework-agnostic, has built-in useSuspenseQuery, devtools, infinite queries, optimistic mutations, and offline support. SWR is a lighter alternative that covers the basics (dedup, caching, revalidation) but has fewer features for complex mutation workflows.

Both give you: request deduplication, stale-while-revalidate caching, automatic retries, and background refresh.

Setup for Vite apps:

// main.tsx
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'

const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 60_000, // 1 minute
      retry: 2,
    },
  },
})

createRoot(document.getElementById('root')!).render(
  <QueryClientProvider client={queryClient}>
    <App />
  </QueryClientProvider>
)

4. Use Suspense for Declarative Loading States

Impact: HIGH — Cleaner code, automatic loading coordination, streaming support.

Suspense lets you declare loading boundaries in the component tree instead of managing isLoading state in every component.

Avoid — manual loading orchestration:

function Dashboard() {
  const { data: user, isLoading: userLoading } = useQuery(userQuery)
  const { data: stats, isLoading: statsLoading } = useQuery(statsQuery)

  if (userLoading || statsLoading) return <FullPageSpinner />
  return (
    <div>
      <UserHeader user={user} />
      <StatsPanel stats={stats} />
    </div>
  )
}

Prefer — Suspense boundaries:

function Dashboard() {
  return (
    <Suspense fallback={<FullPageSpinner />}>
      <DashboardContent />
    </Suspense>
  )
}

function DashboardContent() {
  const { data: user } = useSuspenseQuery(userQuery)
  const { data: stats } = useSuspenseQuery(statsQuery)
  return (
    <div>
      <UserHeader user={user} />
      <StatsPanel stats={stats} />
    </div>
  )
}

For independent sections, use separate Suspense boundaries so they load independently:

function Dashboard() {
  return (
    <div>
      <Suspense fallback={<HeaderSkeleton />}>
        <UserHeader />
      </Suspense>
      <Suspense fallback={<StatsSkeleton />}>
        <StatsPanel />
      </Suspense>
    </div>
  )
}

TanStack Query provides useSuspenseQuery and SWR provides {suspense: true} option.


5. Prefetch Data Before Navigation

Impact: HIGH — Eliminates loading states on page transitions.

Start fetching data before the user commits to a navigation — on hover, focus, or route preload.

With TanStack Query:

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

function ProjectLink({ projectId }: { projectId: string }) {
  const queryClient = useQueryClient()

  const prefetch = () => {
    queryClient.prefetchQuery({
      queryKey: ['project', projectId],
      queryFn: () => fetchProject(projectId),
      staleTime: 30_000,
    })
  }

  return (
    <Link
      to={`/projects/${projectId}`}
      onMouseEnter={prefetch}
      onFocus={prefetch}
    >
      View Project
    </Link>
  )
}

With React Router loaders (Vite apps):

// routes.tsx
const routes = [
  {
    path: '/projects/:id',
    loader: ({ params }) => queryClient.ensureQueryData({
      queryKey: ['project', params.id],
      queryFn: () => fetchProject(params.id!),
    }),
    Component: ProjectPage,
  },
]

6. Use React.cache() for Server-Side Deduplication

Impact: MEDIUM — Deduplicates expensive operations within a single server render.

In server components (RSC), React.cache() ensures the same async call made by multiple components only executes once per request.

import { cache } from 'react'

export const getSession = cache(async () => {
  const session = await auth()
  if (!session?.user?.id) return null
  return session
})

export const getUser = cache(async (userId: string) => {
  return await db.user.findUnique({ where: { id: userId } })
})

Multiple components calling getSession() in the same render share one execution.

Important: Use primitive arguments (strings, numbers) for cache keys. Inline objects create new references and cause cache misses:

// Cache miss every time — new object reference
getUser({ id: '123' })
getUser({ id: '123' }) // miss

// Cache hit — same string value
getUser('123')
getUser('123') // hit

7. Implement Optimistic Updates for Instant Feedback

Impact: HIGH — UI responds immediately without waiting for the server.

For mutations where the outcome is predictable (toggling a like, updating a name), update the UI instantly and reconcile with the server response.

With TanStack Query:

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

function LikeButton({ postId }: { postId: string }) {
  const queryClient = useQueryClient()

  const { mutate: toggleLike } = useMutation({
    mutationFn: () => fetch(`/api/posts/${postId}/like`, { method: 'POST' }),
    onMutate: async () => {
      await queryClient.cancelQueries({ queryKey: ['post', postId] })
      const previous = queryClient.getQueryData<Post>(['post', postId])
      queryClient.setQueryData<Post>(['post', postId], old => ({
        ...old!,
        liked: !old!.liked,
        likeCount: old!.liked ? old!.likeCount - 1 : old!.likeCount + 1,
      }))
      return { previous }
    },
    onError: (_err, _vars, context) => {
      queryClient.setQueryData(['post', postId], context?.previous)
    },
    onSettled: () => {
      queryClient.invalidateQueries({ queryKey: ['post', postId] })
    },
  })

  return <button onClick={() => toggleLike()}>Like</button>
}

8. Avoid Fetch Waterfalls in Component Trees

Impact: CRITICAL — Parent-then-child fetching is the #1 performance problem.

When a parent fetches data and a child fetches its own data based on the parent's result, you create a waterfall. Restructure to fetch in parallel.

Avoid — child can't start until parent finishes:

function UserPage({ userId }: { userId: string }) {
  const { data: user } = useQuery({
    queryKey: ['user', userId],
    queryFn: () => fetchUser(userId),
  })

  if (!user) return <Skeleton />
  return <UserPosts userId={user.id} /> // starts fetching only after user loads
}

function UserPosts({ userId }: { userId: string }) {
  const { data: posts } = useQuery({
    queryKey: ['posts', userId],
    queryFn: () => fetchPosts(userId),
  })
  // ...
}

Prefer — fetch both at the same level:

function UserPage({ userId }: { userId: string }) {
  const { data: user } = useQuery({
    queryKey: ['user', userId],
    queryFn: () => fetchUser(userId),
  })
  const { data: posts } = useQuery({
    queryKey: ['posts', userId],
    queryFn: () => fetchPosts(userId),
  })

  if (!user) return <Skeleton />
  return (
    <div>
      <UserHeader user={user} />
      <PostList posts={posts ?? []} />
    </div>
  )
}

Or use a route-level loader to fetch all data before the component renders.


9. Deduplicate Global Event Listeners

Impact: MEDIUM — Prevents N listeners for N component instances.

When multiple component instances need the same global event (resize, scroll, online), share a single listener.

// hooks/useOnlineStatus.ts
import { useSyncExternalStore } from 'react'

function subscribe(callback: () => void) {
  window.addEventListener('online', callback)
  window.addEventListener('offline', callback)
  return () => {
    window.removeEventListener('online', callback)
    window.removeEventListener('offline', callback)
  }
}

function getSnapshot() {
  return navigator.onLine
}

export function useOnlineStatus() {
  return useSyncExternalStore(subscribe, getSnapshot, () => true)
}

useSyncExternalStore automatically deduplicates subscriptions and ensures consistent state across concurrent renders.


10. Use Passive Event Listeners for Scroll and Touch

Impact: LOW-MEDIUM — Prevents scroll jank from blocking listeners.

Non-passive scroll/touch listeners block the browser's compositor thread. Mark them passive when you don't call preventDefault().

Avoid — blocks scrolling:

useEffect(() => {
  const handler = () => trackScroll(window.scrollY)
  window.addEventListener('scroll', handler)
  return () => window.removeEventListener('scroll', handler)
}, [])

Prefer — non-blocking:

useEffect(() => {
  const handler = () => trackScroll(window.scrollY)
  window.addEventListener('scroll', handler, { passive: true })
  return () => window.removeEventListener('scroll', handler)
}, [])

11. Schema-Version Your Client Storage

Impact: LOW-MEDIUM — Prevents crashes from stale localStorage data.

When reading from localStorage or sessionStorage, stale data from a previous app version can crash your app. Add a schema version and validate.

Avoid — crashes on schema change:

const [prefs, setPrefs] = useState(() => {
  return JSON.parse(localStorage.getItem('prefs') || '{}')
})

Prefer — versioned with fallback:

const PREFS_VERSION = 2

const [prefs, setPrefs] = useState<Prefs>(() => {
  try {
    const raw = localStorage.getItem('prefs')
    if (!raw) return DEFAULT_PREFS
    const parsed = JSON.parse(raw)
    if (parsed._v !== PREFS_VERSION) return DEFAULT_PREFS
    return parsed
  } catch {
    return DEFAULT_PREFS
  }
})

// On save, include version
useEffect(() => {
  localStorage.setItem('prefs', JSON.stringify({ ...prefs, _v: PREFS_VERSION }))
}, [prefs])

Source

Patterns from patterns.dev — framework-agnostic React data fetching guidance for the broader web engineering community.

平台分布

Codex

36.01%
按下载量换算979

Claude

29.84%
按下载量换算812

Cursor

18.29%
按下载量换算497

Gemini CLI

8.21%
按下载量换算223

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。目前只有一个公开来源,建议同时核对源仓库。

继续浏览同类 Skills