React 41: Data Fetching Patterns
easy⏱ 5 mincoursereact
Stale-While-Revalidate
SWR returns cached data immediately (fast!), then fetches fresh data in background. If fresh data differs, UI updates. User gets instant response plus eventual consistency.
// SWR pattern
const { data, error, isLoading, mutate } = useSWR('/api/user', fetcher);
// Automatic features:
// - Caches response
// - Revalidates on focus
// - Deduplicates requests
// - Retries on error
Why not just useEffect?
useEffect requires handling: loading state, error state, race conditions, caching, deduplication, background refresh, retry logic. SWR/Query handle all this. Focus on your UI, not data plumbing.
Build a data fetching hook
Create useData that implements: caching (in-memory), loading/error states, automatic refetch on window focus, and a mutate function to update cache. Demonstrate with a user profile fetcher.