swr

A set of coding rules for SWR, a JavaScript library that loads and caches data in web applications. It covers fetching, refreshing, and changing cached data.

In plain words
What is it for?
Use it when building or reviewing React code that gets data from APIs with SWR. It guides request keys, caching, polling, conditional fetching, and updates.
Why use it?
It helps keep data requests consistent and avoids common problems such as duplicate requests, unclear loading states, and stale results.

Cursor rule

Install

Getting it into your agent

One page per mod, every tool's command on it. A separate URL per tool would split the same page into five that compete with each other.

agentmods
npx agentmods add rules/nedcodes-ok/cursorrules-collection/swr
Clone the repo
git clone --depth 1 https://github.com/nedcodes-ok/cursorrules-collection
Per session 704 This file is loaded in full into every session.
When invoked 704 The same file — it is already loaded in full.
Security scan A 1 finding. Scan, not verified.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5 $0.00704 $0.00704
Opus 5 $0.00352 $0.00352
Sonnet 5 $0.00141 $0.00141
Haiku 4.5 $0.00070 $0.00070

Measured 2d ago against content hash 79a045463ba9, method: parsed. Prices are Anthropic first-party input rates as of 2026-08-30, from the pricing page.

Security

Grade A, and why

swr scanned grade A with 1 finding against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 2d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Makes network callslowCapability

Not a fault in itself. Listed so you know the mod talks to something, and to what.

- Always define a typed fetcher: const fetcher = (url: string) => fetch(url).then(r => r.json()) as Promise<T>
rules-mdc/frameworks/swr.mdc · 54 lines

How it starts

The opening of the file, as written. The whole thing — 54 lines — stays where its author put it; the contents beside it link to each section on GitHub.

SWR Cursor Rules

You are an expert in SWR (stale-while-revalidate). Follow these rules:

Basic Usage

  • Always define a typed fetcher: const fetcher = (url: string) => fetch(url).then(r => r.json()) as Promise
  • Pass a stable key — string or array. Null/undefined/falsy key skips the request
  • Destructure fully: const { data, error, isLoading, isValidating, mutate } = useSWR(key, fetcher)
  • Distinguish isLoading (no data yet) from isValidating (revalidating with existing data)

Key Patterns

  • Use array keys for parameterized requests: useSWR(['/api/users', page], fetcher)
  • Conditional fetching: useSWR(userId ? /api/users/${userId} : null, fetcher)
  • Use useSWR(() => /api/users/${userId}) — function keys throw to pause on missing deps
  • Keep keys deterministic — same params = same key = shared cache

Configuration

  • Set global config via SWRConfig at app root for shared fetcher and options
  • Set revalidateOnFocus: false for data that rarely changes (settings, profiles)
  • Use refreshInterval for polling: useSWR(key, fetcher, { refreshInterval: 5000 })
  • Use dedupingInterval (default 2s) to prevent duplicate requests from multiple components

Mutations

  • Use the bound mutate for local mutations: const { mutate } = useSWR(key, fetcher)
  • Optimistic updates: mutate(newData, { optimisticData: newData, rollbackOnError: true, revalidate: true })
  • Use useSWRMutation for triggered mutations (POST/PUT/DELETE): const { trigger } = useSWRMutation(key, sendRequest)
  • Global mutate for cross-component invalidation: import { mutate } from 'swr'; mutate('/api/users')

Error Handling

  • Check error before rendering data — errors can coexist with stale data
  • Use onErrorRetry in config to customize retry logic (or disable for 4xx)
  • Display stale data with an error banner rather than replacing content with an error page
  • Set errorRetryCount to limit retries: { errorRetryCount: 3 }

Performance

  • Use useSWRInfinite for paginated/infinite scroll data
  • Preload data: preload(key, fetcher) on hover or route prefetch
  • Use the keepPreviousData option to prevent loading flicker during key changes
  • Avoid waterfalls: fetch independent data in parallel with separate useSWR calls

Read the full file on GitHub · 54 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 2d ago First seen · 54 lines · 704 tokens per session scan A 79a045463ba9

Subscribe to this mod's changes

swr is a cursor rule published in the GitHub repository nedcodes-ok/cursorrules-collection (37 stars, last pushed 6mo ago), licensed MIT. It adds 704 tokens to every session, about $0.0035 per session on Opus 5. A static security scan graded it A with 1 finding (makes network calls). No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-30.