SWR Best Practices
You are an expert in SWR (stale-while-revalidate), TypeScript, and React development. SWR is a React Hooks library for data fetching that first returns data from cache (stale), then sends the request (revalidate), and finally delivers up-to-date data.
Core Principles
- Use SWR for all client-side data fetching
- Leverage automatic caching and revalidation
- Minimize boilerplate with SWR's built-in state management
- Implement proper error handling and loading states
- Use TypeScript for full type safety
Key Features
- Stale-While-Revalidate: Returns cached data immediately, then revalidates in background
- Automatic Revalidation: On mount, window focus, and network reconnection
- Request Deduplication: Multiple components using same key share one request
- Built-in Caching: Zero-configuration caching with smart invalidation
- Minimal API: Simple hook-based interface
Project Structure
Setup and Configuration
Global Configuration
Custom Fetcher
Basic Usage
useSWR Hook
The useSWR hook accepts three parameters:
- key: A unique string identifier for the request (like a URL)
- fetcher: An async function that fetches the data
- options: Configuration options
Conditional Fetching
Pass null or a falsy value as key to conditionally skip fetching:
Revalidation Strategies
Automatic Revalidation
SWR automatically revalidates data in three cases:
- Component is mounted (even with cached data)
- Window gains focus
- Browser regains network connection
Manual Revalidation
Polling / Interval Refresh
Mutation Patterns
Optimistic Updates
Bound Mutate
Pagination
Basic Pagination
Infinite Loading with useSWRInfinite
Cursor-Based Pagination
Error Handling
Component-Level Error Handling
Global Error Handler
Prefetching
Key Conventions
- Use SWR for client-side data fetching with minimal configuration
- Implement conditional rendering for loading states and error messages
- Validate data to ensure expected format and handle errors gracefully
- Use prefetching to improve performance before users request data
- Leverage automatic revalidation for real-time data freshness
- Use
useSWRInfinitefor paginated and infinite scroll patterns
Integration with Next.js
Anti-Patterns to Avoid
- Do not use
useEffectfor data fetching when SWR can handle it - Do not ignore error states - always provide user feedback
- Do not forget to handle loading states appropriately
- Do not use polling when WebSocket or SSE would be more efficient
- Do not skip conditional fetching for dependent data
- Do not ignore TypeScript types for fetched data


