react-fetch-cache-patterns
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseExperimental 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, or any data-fetching hookuseSWR - 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或任何数据获取Hook的React组件useSWR - 设计展示大量需加载数据的列表、流或轮播组件
- 排查“后端请求过载”或“页面加载缓慢”等问题
- 在客户端获取、路由加载器、服务端组件或SSR之间做选择
- 实现预取、重试、乐观更新或任何故障处理逻辑
- 重构已实现数据获取但存在请求瀑布、无缓存策略或无并发限制的代码
Rule Categories by Priority
按优先级排序的规则分类
| # | Category | Impact | Prefix | Rules |
|---|---|---|---|---|
| 1 | Request Orchestration | CRITICAL | | 7 |
| 2 | Cache Strategy | CRITICAL | | 7 |
| 3 | Backend Protection | CRITICAL | | 7 |
| 4 | Prefetch & Hydration | HIGH | | 6 |
| 5 | Failure Resilience | HIGH | | 6 |
| 6 | Feed & Carousel Patterns | MEDIUM-HIGH | | 7 |
| 7 | Mutation & Invalidation | MEDIUM | | 4 |
| 8 | Component Patterns | MEDIUM | | 4 |
| # | 分类 | 影响级别 | 前缀 | 规则数量 |
|---|---|---|---|---|
| 1 | 请求编排 | 关键 | | 7 |
| 2 | 缓存策略 | 关键 | | 7 |
| 3 | 后端保护 | 关键 | | 7 |
| 4 | 预取与Hydration | 高 | | 6 |
| 5 | 故障恢复 | 高 | | 6 |
| 6 | 流与轮播模式 | 中高 | | 7 |
| 7 | 突变与缓存失效 | 中 | | 4 |
| 8 | 组件模式 | 中 | | 4 |
Quick Reference
快速参考
1. Request Orchestration (CRITICAL)
1. 请求编排(关键)
- — Use
orch-parallelize-independent-fetchesfor independent requests; never serialPromise.allawait - — Collapse per-row fetches via DataLoader-style batching
orch-batch-n-plus-one-fanout - — One in-flight request per key, shared across subscribers
orch-dedupe-in-flight-requests - — Fetch in parallel with route chunk download
orch-lift-fetch-to-route-loader - — Flatten the dependency graph; only true dependencies wait
orch-avoid-effect-chains - — Move fetches to RSC/server when they don't depend on client state
orch-server-fetch-when-possible - — One bulk request beats N parallel requests
orch-prefer-bulk-endpoint-for-fanout
- — 对独立请求使用
orch-parallelize-independent-fetches;绝不使用串行Promise.allawait - — 通过DataLoader风格的批处理合并每行数据的请求
orch-batch-n-plus-one-fanout - — 每个缓存键仅保留一个进行中的请求,供所有订阅者共享
orch-dedupe-in-flight-requests - — 与路由 chunk 下载并行执行请求
orch-lift-fetch-to-route-loader - — 扁平化依赖图;仅让真正的依赖等待
orch-avoid-effect-chains - — 当请求不依赖客户端状态时,将其移至RSC/服务端执行
orch-server-fetch-when-possible - — 一次批量请求优于N次并行请求
orch-prefer-bulk-endpoint-for-fanout
2. Cache Strategy (CRITICAL)
2. 缓存策略(关键)
- — Canonicalize cache keys; strip undefined, sort arrays
cache-deterministic-keys - — Store each entity once; views hold references
cache-normalize-shared-entities - — Tune
cache-set-stale-timeto data volatility, not refresh frequencystaleTime - — Render stale instantly; revalidate in background
cache-stale-while-revalidate - — Subscribe to slices, not whole objects
cache-select-subscribed-fields - — One typed source of truth for keys; prevents read/write drift
cache-shared-key-factory - — Different
cache-tiered-stale-freshper data class (realtime, fresh, warm, cold, static)staleTime
- — 标准化缓存键;移除未定义值,对数组排序
cache-deterministic-keys - — 每个实体仅存储一次;视图仅保留引用
cache-normalize-shared-entities - — 根据数据波动程度而非刷新频率调整
cache-set-stale-timestaleTime - — 立即渲染过期缓存;在后台重新验证
cache-stale-while-revalidate - — 订阅数据切片,而非整个对象
cache-select-subscribed-fields - — 缓存键的唯一类型化数据源;避免读写不一致
cache-shared-key-factory - — 为不同数据类别设置不同
cache-tiered-stale-fresh(实时、新鲜、温缓存、冷缓存、静态)staleTime
3. Backend Protection (CRITICAL)
3. 后端保护(关键)
- — Cap simultaneous requests with
protect-concurrency-limit-fanout/semaphorep-limit - — In-flight dedup at the fetch layer
protect-collapse-identical-requests - — Wait for user pause before firing search/filter requests
protect-debounce-user-driven-fetches - — Use IntersectionObserver for viewport-triggered fetches
protect-throttle-scroll-triggered - — Add random jitter to prevent thundering-herd retries
protect-jittered-retry-backoff - — Stop calling persistently failing endpoints for a cooldown window
protect-circuit-breaker - — Honor
protect-rate-limit-aware-clientandRetry-AfterheadersX-RateLimit-*
- — 使用
protect-concurrency-limit-fanout/信号量限制同时发起的请求数p-limit - — 在请求层对进行中的重复请求去重
protect-collapse-identical-requests - — 等待用户操作暂停后再触发搜索/筛选请求
protect-debounce-user-driven-fetches - — 使用IntersectionObserver处理视口触发的请求
protect-throttle-scroll-triggered - — 添加随机抖动,避免重试时出现“惊群效应”
protect-jittered-retry-backoff - — 在冷却窗口内停止调用持续失败的接口
protect-circuit-breaker - — 遵循
protect-rate-limit-aware-client和Retry-After响应头X-RateLimit-*
4. Prefetch & Hydration (HIGH)
4. 预取与Hydration(高)
- — Prefetch on hover/pointerdown for instant navigation
prefetch-hover-intent-links - — Parallelize independent queries inside loaders
prefetch-parallel-loader-queries - — Ship server-fetched data via
prefetch-hydrate-server-cache/ RSCHydrationBoundary - — Use
prefetch-idle-likely-nextfor likely-next datarequestIdleCallback - — Fire next-page prefetch via
prefetch-viewport-triggered-next-pagerootMargin - — Tier prefetches by priority; respect
prefetch-budget-and-prioritySave-Data
- — 在悬停/指针按下时预取数据,实现即时导航
prefetch-hover-intent-links - — 在加载器内并行执行独立查询
prefetch-parallel-loader-queries - — 通过
prefetch-hydrate-server-cache/RSC传递服务端获取的数据HydrationBoundary - — 使用
prefetch-idle-likely-next预取可能需要的下一组数据requestIdleCallback - — 通过
prefetch-viewport-triggered-next-page触发下一页数据的预取rootMargin - — 按优先级划分预取层级;遵循
prefetch-budget-and-priority标识Save-Data
5. Failure Resilience (HIGH)
5. 故障恢复(高)
- — Forward
resilience-abort-on-unmountto cancel stale fetchesAbortSignal - — Set per-endpoint timeouts via
resilience-bounded-timeoutsAbortSignal.timeout() - — One boundary per data section, not per page
resilience-scoped-error-boundaries - — Render stale cache when fresh fetch fails
resilience-stale-fallback - — Use idempotency keys or don't auto-retry
resilience-no-auto-retry-mutations - — Critical/important/decorative tiers with different failure modes
resilience-graceful-degradation
- — 传递
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. 流与轮播模式(中高)
- — Use TanStack Virtual for lists > 50 items
feed-virtualize-long-lists - — Cursors beat offset for inserts and large offsets
feed-cursor-pagination - — Carousel summaries lightweight; detail on demand
feed-split-summary-from-detail - — Per-carousel error/Suspense boundaries + tiered fallbacks for homepage feeds
feed-multi-carousel-isolation - — Use entity IDs as keys; never index
feed-stable-keys-across-pages - —
feed-image-lazy-and-sized+ explicit dimensionsloading="lazy" - —
feed-bounded-working-set+ entity LRU eviction for unbounded feedsmaxPages
- — 对超过50条数据的列表使用TanStack Virtual
feed-virtualize-long-lists - — 游标分页优于偏移量分页,适合插入操作和大偏移量场景
feed-cursor-pagination - — 轮播摘要轻量化;详情按需加载
feed-split-summary-from-detail - — 为首页多轮播流设置独立的错误/Suspense边界和分层回退方案
feed-multi-carousel-isolation - — 使用实体ID作为key;绝不用索引
feed-stable-keys-across-pages - — 设置
feed-image-lazy-and-sized+ 明确尺寸loading="lazy" - — 为无限流设置
feed-bounded-working-set+ 实体LRU淘汰机制maxPages
7. Mutation & Invalidation (MEDIUM)
7. 突变与缓存失效(中)
- — Snapshot, optimistic write, rollback on error
mutate-optimistic-updates-with-rollback - — Invalidate specific keys, not entire trees
mutate-surgical-invalidation - — Write mutation responses directly into the cache
mutate-set-data-over-invalidate - — Cancel in-flight queries before optimistic writes
mutate-cancel-queries-on-mutate
- — 快照数据、乐观写入、错误时回滚
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-keysobject keys to keep references stableuseMemo - — Lift fetches; batch via DataLoader; virtualize
render-cap-fanout-in-lists - — One Suspense boundary per data section
render-suspense-per-section - — Put
render-colocate-fetch-with-consumernext to its consumer, not at the rootuseQuery
- — 使用
render-stable-query-keys确保对象类型的查询键引用稳定useMemo - — 提升请求层级;通过DataLoader批处理;使用虚拟化
render-cap-fanout-in-lists - — 为每个数据区块设置独立的Suspense边界
render-suspense-per-section - — 将
render-colocate-fetch-with-consumer放在消费组件旁,而非根组件useQuery
How to Use
使用方法
- Open references/_sections.md for category definitions and impact rationale
- Read individual rule files for incorrect-vs-correct code examples
- For ready-to-use scaffolds, see scaffolding templates
- The AGENTS.md navigation document (auto-generated) provides a TOC for browsing
- 打开references/_sections.md查看分类定义和影响原理
- 阅读单个规则文件查看错误与正确的代码示例
- 如需可直接使用的脚手架,请查看scaffolding templates
- 自动生成的导航文档AGENTS.md提供了完整的目录便于浏览
Scaffolding Templates
脚手架模板
Six ready-to-adapt code templates under :
assets/templates/| Template | Library deps | Purpose |
|---|---|---|
| TanStack Query | Standard query hook with key factory, retry, abort, optional suspense |
| None (pure React + AbortController) | Same patterns as above, library-free: hand-rolled cache, dedup, retry with jitter, staleTime/gcTime, concurrency limit |
| TanStack Query + react-error-boundary | Single carousel (summary + viewport-triggered detail) and multi-carousel feed with per-carousel failure isolation |
| TanStack Query + TanStack Virtual | Cursor-paginated infinite feed with virtualization and bounded working set |
| None | Hover/intent prefetch link wrapper |
| None | In-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 — 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 and templates are zero-dep out of the box.
use-resource-query-no-deps.template.tsxrequest-collapserprefetch-linkassets/templates/| 模板 | 依赖库 | 用途 |
|---|---|---|
| TanStack Query | 标准查询Hook,包含键工厂、重试、取消、可选Suspense |
| 无(纯React + AbortController) | 实现上述相同模式,无依赖:手动实现缓存、去重、带抖动的重试、staleTime/gcTime、并发限制 |
| TanStack Query + react-error-boundary | 单轮播(摘要 + 视口触发详情)和多轮播流,支持每轮播独立故障隔离 |
| TanStack Query + TanStack Virtual | 游标分页无限流,支持虚拟化和有限工作集 |
| 无 | 悬停/意图预取链接包装组件 |
| 无 | 进行中请求去重 + 并发限制工具 |
无依赖方案:如果无法在你的包中添加TanStack Query/SWR/DataLoader(比如体积限制、宿主应用冲突、依赖禁令),请从开始——它仅用React和Web平台API在约250行代码中实现了核心的缓存/去重/重试/取消模式。其他依赖TanStack的模板可基于它适配;只有和模板是开箱即用的无依赖版本。
use-resource-query-no-deps.template.tsxrequest-collapserprefetch-linkReference Files
参考文件
| File | Description |
|---|---|
| references/_sections.md | Category definitions, ordering, impact rationale |
| assets/templates/_template.md | Template for authoring new rules |
| metadata.json | Version, references, abstract |
| 文件 | 描述 |
|---|---|
| references/_sections.md | 分类定义、排序规则、影响原理 |
| assets/templates/_template.md | 编写新规则的模板 |
| metadata.json | 版本、参考链接、摘要 |
Related Skills
相关Skill
- — General React render performance (this skill is data-fetching-specific)
react-optimise - — Bundle/payload optimization for Next.js
nextjs-bundle-optimizer - — Server-side workflow patterns (complements server-fetch guidance)
inngest-nextjs-patterns
- — 通用React渲染性能优化(本Skill专注于数据获取)
react-optimise - — Next.js包/负载优化
nextjs-bundle-optimizer - — 服务端工作流模式(补充服务端请求指导)
inngest-nextjs-patterns