useSWR Hook: Fetching, Loading, and Error States
Use useSWR with custom fetcher functions and handle loading, error, and success states declaratively.
useSWR Hook: Fetching, Loading, and Error States is a free React Academy lesson on CoddyKit — lesson 2 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the React Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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.
The fetcher Function
The fetcher receives the key (or array key spread as arguments) and must return a Promise. The resolved value becomes data. If the fetcher throws, the error property is set.
Example: (url) => fetch(url).then(r => { if (!r.ok) throw new Error(r.status); return r.json(); }).
data and error States
data is undefined while loading for the first time and equals the resolved fetcher value after success. error is undefined unless the fetcher threw, in which case it holds the thrown error object.
Check if (error) to render an error message, and if (!data) to render a loading skeleton, providing clear fallback UIs.
isLoading vs isValidating
isLoading is true only when there is no cached data and a request is in flight: the first-ever load for this key. isValidating is true any time a request is in flight, including background revalidations when cached data already exists.
Use isLoading for skeleton screens; use isValidating for a subtle spinner indicating a background refresh.
Global SWRConfig
SWRConfig lets you define default fetcher, dedupingInterval, refreshInterval, onError handler, and other options for all useSWR calls within its subtree. This centralizes configuration rather than repeating options in every hook.
Nest multiple SWRConfig providers to have different defaults for different sections of your app.
Conditional Fetching with Null Key
Pass null as the key to skip the request: useSWR(isLoggedIn ? '/api/user' : null, fetcher). SWR will not fetch until the key becomes a non-null value.
This is cleaner than the skip option in React Query. The key transitioning from null to a string automatically triggers the first fetch.
Dependent Fetching
Chain SWR hooks for dependent requests: const { data: user } = useSWR('/api/me', fetcher) then const { data: orders } = useSWR(user ? '/api/orders/' + user.id : null, fetcher). The second hook waits until the first resolves.
This pattern avoids useEffect chains and keeps data dependencies declarative and readable.
Request Deduplication in Action
If a Header component and a Sidebar component both call useSWR('/api/user', fetcher), SWR fires only one request and shares the result. Both components re-render together when data or error updates.
This deduplication happens automatically within the dedupingInterval window (default 2000ms) without any extra configuration.
Useful SWR Options
refreshInterval: 5000 polls every 5 seconds. refreshWhenHidden: false stops polling when the tab is not visible. shouldRetryOnError: false disables automatic retry. revalidateOnFocus: false disables focus-triggered revalidation.
Combine options to match your data freshness requirements: dashboards often use refreshInterval, while static content sets revalidateOnFocus: false.
Pagination with useSWR
For paginated data, include the page number in the key: useSWR(['/api/items', page], fetcher). Changing page triggers a new fetch for that page while caching previous pages.
SWR also provides useSWRInfinite for cursor-based or infinite scroll patterns with a getKey function that builds keys based on page index and previous page data.
SWR Key as Null
What happens when you pass null as the key to useSWR?
Lesson Recap
useSWR(key, fetcher) returns data, error, isLoading, and isValidating. Null keys disable fetching for conditional and dependent requests. isLoading indicates the first load; isValidating indicates any in-flight request. SWRConfig centralizes defaults, and request deduplication across components is automatic.
Options like refreshInterval, revalidateOnFocus, and shouldRetryOnError fine-tune data freshness behavior per hook or globally.
Frequently asked questions
Is the “useSWR Hook: Fetching, Loading, and Error States” lesson free?
Yes — the full text of “useSWR Hook: Fetching, Loading, and Error States” is free to read here on the web, and the React Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the React Academy course, upgrade to CoddyKit PRO.
What will I learn in “useSWR Hook: Fetching, Loading, and Error States”?
Use useSWR with custom fetcher functions and handle loading, error, and success states declaratively. You practise React Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start React Academy?
No prior experience is required. React Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 2 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “useSWR Hook: Fetching, Loading, and Error States” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this React Academy lesson?
Yes. Every React Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
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