In useSWR, both isLoading and isValidating represent states of the data-fetching process, but they serve different purposes:
- Definition: Indicates the very first fetch for the given SWR key.
- State:
trueonly when there is no cached data and the fetch is in progress. - Lifecycle:
- Active during the initial fetch when no data exists.
- Becomes
falseonce data is fetched or available in the cache.
- A new resource is requested with no prior cache.
isLoadingwill betrueuntil the data is fetched.
- Definition: Indicates whether a fetch request is in progress (regardless of whether there’s cached data).
- State:
truewhenever SWR is actively fetching, even if there’s stale data available. - Lifecycle:
- Active during the initial fetch or when revalidating stale data.
- Becomes
falsewhen no fetch is in progress.
- A resource is requested, and cached data is available.
- SWR serves the cached data but starts revalidating it.
isValidatingwill betrueduring the revalidation, butisLoadingwill remainfalsesince cached data exists.
| Property | isLoading |
isValidating |
|---|---|---|
| First Fetch | true |
true |
| Revalidation | false (cached data exists) |
true |
| Cache Status | Ignores cached data | Works with cached data |
| Focus Events | false |
true |
import useSWR from 'swr';
function ExampleComponent() {
const { data, isLoading, isValidating } = useSWR('/api/resource');
if (isLoading) return <p>Loading for the first time...</p>; // No data, first fetch.
if (isValidating) return <p>Revalidating stale data...</p>; // Data available, validating.
return <p>Data: {JSON.stringify(data)}</p>;
}isLoading: Use for the initial "no data yet" loading state.isValidating: Use for indicating ongoing fetches (even if stale data is displayed). It's particularly useful for scenarios like showing a "refreshing" state while background revalidation occurs.
Use isLoading for a "first-time load" state and isValidating for any active fetch (including revalidations). These states can also be combined for more nuanced handling.