useSWR Hook: Fetching, Loading, and Error States
Use useSWR with custom fetcher functions and handle loading, error, and success states declaratively.
The useSWR Signature
useSWR(key, fetcher, options) is the primary hook. key is the cache key (usually a URL string), fetcher is the async function that returns data, and options is an optional configuration object.
The hook returns an object with data, error, isLoading, isValidating, and the mutate function.
The key Parameter
The key can be a string URL, an array of [url, params], or null. String keys map to simple GET requests. Array keys allow you to embed variables like userId or filters into the cache identity.
Passing null disables the request entirely, useful for conditional fetching when required data is not yet available.
All lessons in this course
- SWR Core Concepts: Stale-While-Revalidate
- useSWR Hook: Fetching, Loading, and Error States
- Mutation and Optimistic Updates with SWR
- SWR vs React Query: Choosing the Right Tool