react-fetch-cache-patterns

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Experimental React Data Fetching & Caching Best Practices

实验性React数据获取与缓存最佳实践

Implementation patterns for React applications that fetch and cache many API requests without overwhelming the backend. 48 rules across 8 categories, ordered by execution lifecycle impact — earlier categories cascade through everything downstream. Templates show both library-based (TanStack Query, SWR) and library-free (pure React + AbortController) implementations so the patterns are usable regardless of stack constraints.
本文介绍了React应用中获取并缓存大量API请求、同时避免压垮后端的实现模式。涵盖8个分类共48条规则,按执行生命周期影响排序——靠前的分类会影响后续所有环节。模板同时提供了基于库(TanStack Query、SWR)和无依赖(纯React + AbortController)的实现方式,因此无论技术栈限制如何,这些模式都可复用。

When to Apply

适用场景

  • Writing or reviewing a React component that calls
    fetch
    ,
    useQuery
    ,
    useSWR
    , or any data-fetching hook
  • Designing a list, feed, or carousel that displays many items each requiring data
  • Investigating "the backend is getting hammered" or "the page loads slowly" symptoms
  • Choosing between client-side fetching, route loaders, server components, or SSR
  • Implementing prefetch, retry, optimistic updates, or any failure-handling logic
  • Refactoring code that already does data fetching but with waterfalls, no cache strategy, or no concurrency limits
  • 编写或审查调用
    fetch
    useQuery
    useSWR
    或任何数据获取Hook的React组件
  • 设计展示大量需加载数据的列表、流或轮播组件
  • 排查“后端请求过载”或“页面加载缓慢”等问题
  • 在客户端获取、路由加载器、服务端组件或SSR之间做选择
  • 实现预取、重试、乐观更新或任何故障处理逻辑
  • 重构已实现数据获取但存在请求瀑布、无缓存策略或无并发限制的代码

Rule Categories by Priority

按优先级排序的规则分类

#CategoryImpactPrefixRules
1Request OrchestrationCRITICAL
orch-
7
2Cache StrategyCRITICAL
cache-
7
3Backend ProtectionCRITICAL
protect-
7
4Prefetch & HydrationHIGH
prefetch-
6
5Failure ResilienceHIGH
resilience-
6
6Feed & Carousel PatternsMEDIUM-HIGH
feed-
7
7Mutation & InvalidationMEDIUM
mutate-
4
8Component PatternsMEDIUM
render-
4
#分类影响级别前缀规则数量
1请求编排关键
orch-
7
2缓存策略关键
cache-
7
3后端保护关键
protect-
7
4预取与Hydration
prefetch-
6
5故障恢复
resilience-
6
6流与轮播模式中高
feed-
7
7突变与缓存失效
mutate-
4
8组件模式
render-
4

Quick Reference

快速参考

1. Request Orchestration (CRITICAL)

1. 请求编排(关键)

  • orch-parallelize-independent-fetches
    — Use
    Promise.all
    for independent requests; never serial
    await
  • orch-batch-n-plus-one-fanout
    — Collapse per-row fetches via DataLoader-style batching
  • orch-dedupe-in-flight-requests
    — One in-flight request per key, shared across subscribers
  • orch-lift-fetch-to-route-loader
    — Fetch in parallel with route chunk download
  • orch-avoid-effect-chains
    — Flatten the dependency graph; only true dependencies wait
  • orch-server-fetch-when-possible
    — Move fetches to RSC/server when they don't depend on client state
  • orch-prefer-bulk-endpoint-for-fanout
    — One bulk request beats N parallel requests
  • orch-parallelize-independent-fetches
    — 对独立请求使用
    Promise.all
    ;绝不使用串行
    await
  • orch-batch-n-plus-one-fanout
    — 通过DataLoader风格的批处理合并每行数据的请求
  • orch-dedupe-in-flight-requests
    — 每个缓存键仅保留一个进行中的请求,供所有订阅者共享
  • orch-lift-fetch-to-route-loader
    — 与路由 chunk 下载并行执行请求
  • orch-avoid-effect-chains
    — 扁平化依赖图;仅让真正的依赖等待
  • orch-server-fetch-when-possible
    — 当请求不依赖客户端状态时,将其移至RSC/服务端执行
  • orch-prefer-bulk-endpoint-for-fanout
    — 一次批量请求优于N次并行请求

2. Cache Strategy (CRITICAL)

2. 缓存策略(关键)

  • cache-deterministic-keys
    — Canonicalize cache keys; strip undefined, sort arrays
  • cache-normalize-shared-entities
    — Store each entity once; views hold references
  • cache-set-stale-time
    — Tune
    staleTime
    to data volatility, not refresh frequency
  • cache-stale-while-revalidate
    — Render stale instantly; revalidate in background
  • cache-select-subscribed-fields
    — Subscribe to slices, not whole objects
  • cache-shared-key-factory
    — One typed source of truth for keys; prevents read/write drift
  • cache-tiered-stale-fresh
    — Different
    staleTime
    per data class (realtime, fresh, warm, cold, static)
  • cache-deterministic-keys
    — 标准化缓存键;移除未定义值,对数组排序
  • cache-normalize-shared-entities
    — 每个实体仅存储一次;视图仅保留引用
  • cache-set-stale-time
    — 根据数据波动程度而非刷新频率调整
    staleTime
  • cache-stale-while-revalidate
    — 立即渲染过期缓存;在后台重新验证
  • cache-select-subscribed-fields
    — 订阅数据切片,而非整个对象
  • cache-shared-key-factory
    — 缓存键的唯一类型化数据源;避免读写不一致
  • cache-tiered-stale-fresh
    — 为不同数据类别设置不同
    staleTime
    (实时、新鲜、温缓存、冷缓存、静态)

3. Backend Protection (CRITICAL)

3. 后端保护(关键)

  • protect-concurrency-limit-fanout
    — Cap simultaneous requests with
    p-limit
    /semaphore
  • protect-collapse-identical-requests
    — In-flight dedup at the fetch layer
  • protect-debounce-user-driven-fetches
    — Wait for user pause before firing search/filter requests
  • protect-throttle-scroll-triggered
    — Use IntersectionObserver for viewport-triggered fetches
  • protect-jittered-retry-backoff
    — Add random jitter to prevent thundering-herd retries
  • protect-circuit-breaker
    — Stop calling persistently failing endpoints for a cooldown window
  • protect-rate-limit-aware-client
    — Honor
    Retry-After
    and
    X-RateLimit-*
    headers
  • protect-concurrency-limit-fanout
    — 使用
    p-limit
    /信号量限制同时发起的请求数
  • protect-collapse-identical-requests
    — 在请求层对进行中的重复请求去重
  • protect-debounce-user-driven-fetches
    — 等待用户操作暂停后再触发搜索/筛选请求
  • protect-throttle-scroll-triggered
    — 使用IntersectionObserver处理视口触发的请求
  • protect-jittered-retry-backoff
    — 添加随机抖动,避免重试时出现“惊群效应”
  • protect-circuit-breaker
    — 在冷却窗口内停止调用持续失败的接口
  • protect-rate-limit-aware-client
    — 遵循
    Retry-After
    X-RateLimit-*
    响应头

4. Prefetch & Hydration (HIGH)

4. 预取与Hydration(高)

  • prefetch-hover-intent-links
    — Prefetch on hover/pointerdown for instant navigation
  • prefetch-parallel-loader-queries
    — Parallelize independent queries inside loaders
  • prefetch-hydrate-server-cache
    — Ship server-fetched data via
    HydrationBoundary
    / RSC
  • prefetch-idle-likely-next
    — Use
    requestIdleCallback
    for likely-next data
  • prefetch-viewport-triggered-next-page
    — Fire next-page prefetch via
    rootMargin
  • prefetch-budget-and-priority
    — Tier prefetches by priority; respect
    Save-Data
  • prefetch-hover-intent-links
    — 在悬停/指针按下时预取数据,实现即时导航
  • prefetch-parallel-loader-queries
    — 在加载器内并行执行独立查询
  • prefetch-hydrate-server-cache
    — 通过
    HydrationBoundary
    /RSC传递服务端获取的数据
  • prefetch-idle-likely-next
    — 使用
    requestIdleCallback
    预取可能需要的下一组数据
  • prefetch-viewport-triggered-next-page
    — 通过
    rootMargin
    触发下一页数据的预取
  • prefetch-budget-and-priority
    — 按优先级划分预取层级;遵循
    Save-Data
    标识

5. Failure Resilience (HIGH)

5. 故障恢复(高)

  • resilience-abort-on-unmount
    — Forward
    AbortSignal
    to cancel stale fetches
  • resilience-bounded-timeouts
    — Set per-endpoint timeouts via
    AbortSignal.timeout()
  • resilience-scoped-error-boundaries
    — One boundary per data section, not per page
  • resilience-stale-fallback
    — Render stale cache when fresh fetch fails
  • resilience-no-auto-retry-mutations
    — Use idempotency keys or don't auto-retry
  • resilience-graceful-degradation
    — Critical/important/decorative tiers with different failure modes
  • resilience-abort-on-unmount
    — 传递
    AbortSignal
    以取消过期请求
  • resilience-bounded-timeouts
    — 通过
    AbortSignal.timeout()
    为每个接口设置超时时间
  • resilience-scoped-error-boundaries
    — 为每个数据区块设置独立的错误边界,而非整页设置
  • resilience-stale-fallback
    — 当新请求失败时,渲染过期缓存
  • resilience-no-auto-retry-mutations
    — 使用幂等键或禁止自动重试
  • resilience-graceful-degradation
    — 按关键/重要/装饰性划分层级,设置不同故障模式

6. Feed & Carousel Patterns (MEDIUM-HIGH)

6. 流与轮播模式(中高)

  • feed-virtualize-long-lists
    — Use TanStack Virtual for lists > 50 items
  • feed-cursor-pagination
    — Cursors beat offset for inserts and large offsets
  • feed-split-summary-from-detail
    — Carousel summaries lightweight; detail on demand
  • feed-multi-carousel-isolation
    — Per-carousel error/Suspense boundaries + tiered fallbacks for homepage feeds
  • feed-stable-keys-across-pages
    — Use entity IDs as keys; never index
  • feed-image-lazy-and-sized
    loading="lazy"
    + explicit dimensions
  • feed-bounded-working-set
    maxPages
    + entity LRU eviction for unbounded feeds
  • feed-virtualize-long-lists
    — 对超过50条数据的列表使用TanStack Virtual
  • feed-cursor-pagination
    — 游标分页优于偏移量分页,适合插入操作和大偏移量场景
  • feed-split-summary-from-detail
    — 轮播摘要轻量化;详情按需加载
  • feed-multi-carousel-isolation
    — 为首页多轮播流设置独立的错误/Suspense边界和分层回退方案
  • feed-stable-keys-across-pages
    — 使用实体ID作为key;绝不用索引
  • feed-image-lazy-and-sized
    — 设置
    loading="lazy"
    + 明确尺寸
  • feed-bounded-working-set
    — 为无限流设置
    maxPages
    + 实体LRU淘汰机制

7. Mutation & Invalidation (MEDIUM)

7. 突变与缓存失效(中)

  • mutate-optimistic-updates-with-rollback
    — Snapshot, optimistic write, rollback on error
  • mutate-surgical-invalidation
    — Invalidate specific keys, not entire trees
  • mutate-set-data-over-invalidate
    — Write mutation responses directly into the cache
  • mutate-cancel-queries-on-mutate
    — Cancel in-flight queries before optimistic writes
  • mutate-optimistic-updates-with-rollback
    — 快照数据、乐观写入、错误时回滚
  • mutate-surgical-invalidation
    — 失效特定缓存键,而非整个缓存树
  • mutate-set-data-over-invalidate
    — 将突变响应直接写入缓存
  • mutate-cancel-queries-on-mutate
    — 在乐观写入前取消进行中的查询

8. Component Patterns (MEDIUM)

8. 组件模式(中)

  • render-stable-query-keys
    useMemo
    object keys to keep references stable
  • render-cap-fanout-in-lists
    — Lift fetches; batch via DataLoader; virtualize
  • render-suspense-per-section
    — One Suspense boundary per data section
  • render-colocate-fetch-with-consumer
    — Put
    useQuery
    next to its consumer, not at the root
  • render-stable-query-keys
    — 使用
    useMemo
    确保对象类型的查询键引用稳定
  • render-cap-fanout-in-lists
    — 提升请求层级;通过DataLoader批处理;使用虚拟化
  • render-suspense-per-section
    — 为每个数据区块设置独立的Suspense边界
  • render-colocate-fetch-with-consumer
    — 将
    useQuery
    放在消费组件旁,而非根组件

How to Use

使用方法

  1. Open references/_sections.md for category definitions and impact rationale
  2. Read individual rule files for incorrect-vs-correct code examples
  3. For ready-to-use scaffolds, see scaffolding templates
  4. The AGENTS.md navigation document (auto-generated) provides a TOC for browsing
  1. 打开references/_sections.md查看分类定义和影响原理
  2. 阅读单个规则文件查看错误与正确的代码示例
  3. 如需可直接使用的脚手架,请查看scaffolding templates
  4. 自动生成的导航文档AGENTS.md提供了完整的目录便于浏览

Scaffolding Templates

脚手架模板

Six ready-to-adapt code templates under
assets/templates/
:
TemplateLibrary depsPurpose
use-resource-query.template.tsx
TanStack QueryStandard query hook with key factory, retry, abort, optional suspense
use-resource-query-no-deps.template.tsx
None (pure React + AbortController)Same patterns as above, library-free: hand-rolled cache, dedup, retry with jitter, staleTime/gcTime, concurrency limit
carousel-data-loader.template.tsx
TanStack Query + react-error-boundarySingle carousel (summary + viewport-triggered detail) and multi-carousel feed with per-carousel failure isolation
infinite-feed.template.tsx
TanStack Query + TanStack VirtualCursor-paginated infinite feed with virtualization and bounded working set
prefetch-link.template.tsx
NoneHover/intent prefetch link wrapper
request-collapser.template.ts
NoneIn-flight deduplication + concurrency limit utility
Library-free path: if you can't add TanStack Query / SWR / DataLoader to your bundle (size constraints, host-app conflicts, dependency bans), start with
use-resource-query-no-deps.template.tsx
— it implements the core cache/dedup/retry/abort patterns in ~250 lines using only React and the web platform. The other templates that depend on TanStack can be adapted on top of it; only the
request-collapser
and
prefetch-link
templates are zero-dep out of the box.
assets/templates/
下有6个可直接适配的代码模板:
模板依赖库用途
use-resource-query.template.tsx
TanStack Query标准查询Hook,包含键工厂、重试、取消、可选Suspense
use-resource-query-no-deps.template.tsx
(纯React + AbortController)实现上述相同模式,无依赖:手动实现缓存、去重、带抖动的重试、staleTime/gcTime、并发限制
carousel-data-loader.template.tsx
TanStack Query + react-error-boundary单轮播(摘要 + 视口触发详情)多轮播流,支持每轮播独立故障隔离
infinite-feed.template.tsx
TanStack Query + TanStack Virtual游标分页无限流,支持虚拟化和有限工作集
prefetch-link.template.tsx
悬停/意图预取链接包装组件
request-collapser.template.ts
进行中请求去重 + 并发限制工具
无依赖方案:如果无法在你的包中添加TanStack Query/SWR/DataLoader(比如体积限制、宿主应用冲突、依赖禁令),请从
use-resource-query-no-deps.template.tsx
开始——它仅用React和Web平台API在约250行代码中实现了核心的缓存/去重/重试/取消模式。其他依赖TanStack的模板可基于它适配;只有
request-collapser
prefetch-link
模板是开箱即用的无依赖版本。

Reference Files

参考文件

FileDescription
references/_sections.mdCategory definitions, ordering, impact rationale
assets/templates/_template.mdTemplate for authoring new rules
metadata.jsonVersion, references, abstract
文件描述
references/_sections.md分类定义、排序规则、影响原理
assets/templates/_template.md编写新规则的模板
metadata.json版本、参考链接、摘要

Related Skills

相关Skill

  • react-optimise
    — General React render performance (this skill is data-fetching-specific)
  • nextjs-bundle-optimizer
    — Bundle/payload optimization for Next.js
  • inngest-nextjs-patterns
    — Server-side workflow patterns (complements server-fetch guidance)
  • react-optimise
    — 通用React渲染性能优化(本Skill专注于数据获取)
  • nextjs-bundle-optimizer
    — Next.js包/负载优化
  • inngest-nextjs-patterns
    — 服务端工作流模式(补充服务端请求指导)