RepoPilot

vercel / swr

Search vercel/swr

GitHub

Code

Understand vercel/swr's source layout and find a starting point for your task using the saved repository evidence.

Detailed import-graph metrics were not captured for this report.

How the code fits together

AI
  • Entry Points & ExportsPublic API surfaces for different hook variants and use cases.
  • Core Utilities & CacheCache management, configuration, and shared utilities powering all hooks.
  • Internal State & EventsGlobal state management, event broadcasting, and subscription handling.
  • Configuration & EnvironmentEnvironment detection, preset configurations, and context providers.
  • Build & PackagingTypeScript configuration, build tooling, and package exports.

Files at 9ed1240a4cf7 · descriptions are AI-written.

Where to start reading

  1. Repository root
  2. Suggested starting pointAI
  3. Suggested starting pointAI
  4. Suggested starting pointAI

Find files for a task

AI

Add a new hook variant (e.g., useSWRFoo)

Suggested by the saved analysis. Some step paths were not captured or refer to generated or vendor files; only observed source files are linked.

  • Export hook and types from root package.json exports map

Add a global configuration option

Suggested by the saved analysis. Verify the proposed change against these source files.

  • Extend type definition in src/_internal/types.ts (SWRConfig interface)
  • Add default value to src/_internal/utils/config.ts defaultConfig object
  • Use config value in appropriate utility (e.g., mutate.ts, cache.ts) via resolveConfig

Add middleware/plugin support

Suggested by the saved analysis. Verify the proposed change against these source files.

  • Define middleware type in src/_internal/types.ts (Middleware interface)
  • Implement middleware chain logic in src/_internal/utils/with-middleware.ts
  • Integrate middleware execution into useSWR hook initialization

Change the public API

Start at the entry points declared by the captured manifest, then trace their implementation and tests.

  • Check the root package configuration before choosing a workspace or command.

Add or update tests

Use a nearby test as a pattern. Read the root manifest or contribution guide for the correct test command. These suggestions use file names, not verified execution paths.

  • File-name match for this task.
  • File-name match for this task.
  • File-name match for this task.

Change build or automation

Inspect the relevant configuration and the commands it runs before changing the workflow. These suggestions use file names, not verified execution paths.

  • File-name match for this task.
  • File-name match for this task.
  • File-name match for this task.

File paths come from a snapshot of up to 500 captured paths; an omitted file may still exist.

  • Some manifest entry targets are generated output or are absent from the captured source paths. Their source implementation has not been established.

Architecture and request flow

Start here — files every contributor must understand

AI · unverified
1
src/index/use-swr.ts

Primary hook entry point implementing the core SWR data-fetching logic with cache, revalidation, and subscription management.

2
src/_internal/utils/cache.ts

Implements the stale-while-revalidate cache storage and lookup mechanism that underpins all data fetching.

3
src/_internal/utils/config.ts

Defines default configuration options and merging logic for global and per-hook SWR settings.

4
src/_internal/index.ts

Internal exports barrel for utilities, types, and helpers used across hook implementations.

5
src/infinite/index.ts

Pagination-aware hook variant extending core SWR for infinite scroll and paginated data patterns.

6
src/mutation/index.ts

Mutation hook for handling data mutations with optimistic updates and revalidation strategies.

7
package.json

Root package manifest defining build targets, exports, pnpm workspace configuration, and React version requirements.

Request flow

Technology choices

React Hooks API

Provides composable state and lifecycle management for function components without class boilerplate.

Stale-While-Revalidate (RFC 5861)

Balances perceived performance (immediate stale data) with data freshness (background revalidation).

pnpm monorepo workspace

Enables independent sub-packages (swr/infinite, swr/mutation, swr/subscription) while sharing core code.

TypeScript with SWC transpilation

Provides type safety and faster build times compared to Babel; supports React Server Components via conditional exports.

Build time and runtime

Build-time

  • ▸
    TypeScript Compilation — Compiles .ts/.tsx to .js/.mjs with declaration files (.d.ts/.d.mts) via tsc or SWC.
  • ▸
    Conditional Exports — package.json exports map routes to react-server or browser implementations based on environment.
  • ▸
    Bundle Tree-Shaking — Monorepo sub-packages enable consumers to import only needed variants (e.g., swr/infinite).

Runtime

  • ▸
    Cache Lookup & Subscription — O(1) cache hit for identical keys; event listeners broadcast updates across subscribed hooks.
  • ▸
    Fetcher Execution & Deduplication — Concurrent identical requests coalesced into single fetch via internal promise deduplication.
  • ▸
    Revalidation Scheduling — Focus/visibility events, polling intervals, and manual mutation triggers orchestrate background refetches.
  • ▸
    React Server Component Support — index.react-server.ts exports preload and server-side utilities for RSC contexts (no hooks).

Design trade-offs

Global cache state shared across all component instances

Eliminates data duplication and enables automatic deduplication of identical requests.

Cache is not isolated per component; context pollution possible if multiple SWR providers co-exist.

Stale-while-revalidate over always-fresh data

Reduces perceived latency by serving cached data immediately while fetching in background.

Users may see stale data momentarily; applications requiring absolute freshness need custom revalidation logic.

Separate hook variants (useSWR, useSWRInfinite, useSWRMutation) over monolithic hook

Reduces bundle size for applications using only specific variants; simpler API per use case.

More imports to manage; code duplication across variants; integration complexity if mixing variants.

Non-goals

  • ✗Real-time bidirectional synchronization (useSWRSubscription is event-driven, not WebSocket-native)
  • ✗Built-in authentication or authorization enforcement
  • ✗Server-side rendering state hydration without manual setup
  • ✗Offline-first local persistence (no built-in IndexedDB/localStorage sync)

Code quality and hotspots

Quality Score: 80/100

Low Risk

This repo is in good health with CI, tests, and active maintenance.

High complexity -10Multiple anti-patterns -10

Maintainability grade

Static analysis

How maintainable the code looks — from complexity, code issues, test presence, file size, and hotspot load. It grades the shape of the code, not defect risk, and doesn't replace review.

C
65/100
A ≥ 85, B ≥ 70, C ≥ 55, D ≥ 40, F < 40
Cyclomatic complexityavg 24
10/35
Code issues0 errors, 12 warnings
15/20
Testspresent · ~100% of files
20/20
Largest file1,215 lines
10/15
Hotspot load0 high-risk files
10/10

Configuration status

CI/CD Pipeline — configured

Provider: GitHub Actions

5 GitHub Actions workflows

Test Suite — detected

140 test files detected

Stack: Jest/Vitest

Where: test/e2e · test/e2e/site/app/partially-hydrate · test/e2e/site/app

Test Coverage — ~100%heuristic

140 test files / 133 source files. This is a file-count ratio, not real line coverage — set up Codecov for authoritative numbers.

Dependency Scanning — no config detected

No Dependabot / Renovate / Snyk / Trivy / CodeQL config found. Enable Dependabot or Renovate.

Top hotspots

Files edited often AND hard to reason about. Churn = recent commit frequency, Complexity = branches and nesting, Risk = both combined. These are the highest-leverage targets for refactoring or testing.

index/use-swr.ts
Churn: 28 (7 commits/180d)Complexity: 100Risk: 28
utils/cache.ts
Churn: 12 (3 commits/180d)Complexity: 93Risk: 11

All hotspots

Files that change often and are complex tend to accumulate more bugs

AI-suggested anti-patterns

AI · unverified

Pattern-matches from the file structure and dependencies — useful as hypotheses, but not grounded in actual source. For real findings see Code Scanning above.

Global mutable cache without isolation

Medium

All hook instances share a single Map-based cache; no per-instance or per-tenant isolation; potential data leakage in multi-tenant scenarios.

src/_internal/utils/global-state.ts

Error silent failure in mutation revalidation

Medium

Revalidation errors after mutation success are caught silently; consumers may not detect partial failures.

src/mutation/index.ts

No validation of fetcher function signature

Low

Hook does not validate that fetcher is callable or returns a Promise; runtime errors only occur on invocation.

src/index/use-swr.ts

Unbounded cache growth in long-lived apps

High

Cache keys never expire or are evicted; memory usage grows indefinitely as new keys are fetched.

src/_internal/utils/cache.ts

AI-suggested bottlenecks

AI · unverified

Speculation from file structure, not profiling data. Validate against real metrics before acting on these.

Memory & CPU Bottleneck

Cache lookup and update operations are synchronous and unoptimized; linear scan on large caches.

src/_internal/utils/cache.ts

CPU Bottleneck

Cache key serialization may be expensive for deeply nested or large objects; no memoization.

src/_internal/utils/serialize.ts

CPU Bottleneck

Event broadcasting to all subscribers on a key is O(n) subscribers; no batch updates.

src/index/use-swr.ts

Code metrics

Static analysis on sampled source files (up to 15 files).

Avg Cyclomatic Complexity24

Counts if/for/while/switch/catch/ternary branches

Errors / Warnings0 / 12

Secrets, empty catches, console.log, var usage, long lines

Largest File Analyzed1215 lines
src/_internal/types.ts