SWR (stale-while-revalidate) provides elegant data fetching for React. Here's how to use it effectively.
Basic Setup#
Basic Data Fetching#
Conditional Fetching#
Mutation and Revalidation#
Optimistic Updates#
Pagination#
Error Handling#
Preloading#
Best Practices#
Keys:
✓ Use consistent key patterns
✓ Include all dependencies in key
✓ Use null to skip fetching
✓ Consider key serialization
Caching:
✓ Set appropriate dedupingInterval
✓ Use keepPreviousData for pagination
✓ Configure revalidation strategies
✓ Use fallback for SSR
Mutations:
✓ Use optimistic updates for UX
✓ Always handle rollback
✓ Revalidate related data
✓ Show loading states
Conclusion#
SWR provides elegant, declarative data fetching with built-in caching and revalidation. Use optimistic updates for responsive UIs, infinite loading for lists, and proper error handling for resilience. The stale-while-revalidate strategy ensures users always see data quickly while keeping it fresh.