Skip to content

Instantly share code, notes, and snippets.

@bonniss
Created December 12, 2024 14:28
Show Gist options
  • Save bonniss/2cc22c28c9d93562485a98c786abaed7 to your computer and use it in GitHub Desktop.
Save bonniss/2cc22c28c9d93562485a98c786abaed7 to your computer and use it in GitHub Desktop.

In useSWR, both isLoading and isValidating represent states of the data-fetching process, but they serve different purposes:


isLoading

  • Definition: Indicates the very first fetch for the given SWR key.
  • State: true only when there is no cached data and the fetch is in progress.
  • Lifecycle:
    • Active during the initial fetch when no data exists.
    • Becomes false once data is fetched or available in the cache.

Example Scenario:

  1. A new resource is requested with no prior cache.
  2. isLoading will be true until the data is fetched.

isValidating

  • Definition: Indicates whether a fetch request is in progress (regardless of whether there’s cached data).
  • State: true whenever SWR is actively fetching, even if there’s stale data available.
  • Lifecycle:
    • Active during the initial fetch or when revalidating stale data.
    • Becomes false when no fetch is in progress.

Example Scenario:

  1. A resource is requested, and cached data is available.
  2. SWR serves the cached data but starts revalidating it.
  3. isValidating will be true during the revalidation, but isLoading will remain false since cached data exists.

Key Differences

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

Practical Example

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>;
}

When to Use Each

  • 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.

Conclusion:

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment