intermediate
SWR
Apply stale-while-revalidate semantics, cache keys, revalidation triggers, mutation, and lightweight fetching.
SWR implements stale-while-revalidate: show cached data immediately, revalidate in the background. `useSWR(key, fetcher)` deduplicates requests and refetches on focus/reconnect by default.
const { data, error, isLoading, mutate } = useSWR('/api/user', fetcher);
// mutate(localData, false) — optimistic local update without revalidate
| Feature | SWR default feel | |---------|------------------| | Cache key | String or tuple from hook key | | Revalidate | Focus, reconnect, interval optional | | Mutations | `mutate` for local cache updates |
Compared to TanStack Query, SWR API is smaller; complex invalidation graphs and mutation tooling are richer in TanStack Query. Choose based on team needs and cache complexity.
The trade-off is minimal API and stale-while-revalidate UX versus fewer built-in mutation primitives than TanStack Query.
On interviews: explain SWR cache key = fetch identity; when `mutate` beats refetch.
Common pitfalls: same key for different fetchers, missing error handling, and optimistic mutate without rollback.
Checklist:
- Stable keys per resource + params.
- Configure revalidate triggers per UX.
- mutate for optimistic paths.
- Pair with global fetcher for auth headers.