← Back to React Course | Chapter 10: Data Fetching & Async | Lesson 7 of 10

SWR से Data Fetching

SWR एक food delivery app जैसा है जो आपको instantly yesterday का saved menu दिखाता है जबकि यह quietly check करता है कि आज का menu बदला है या नहीं।
Syntax
markup
const fetcher = url => fetch(url).then(res => res.json());

const { data, error, isLoading } = useSWR("/api/path", fetcher);

Stale-While-Revalidate का Idea

SWR का core idea, और इसका namesake, cached (stale) data को user को तुरंत दिखाना है, जबकि simultaneously background में एक fresh request fire करके इसे revalidate करना है।

यह UI को एक slow connection पर भी instant feel कराता है, fresh data आने पर seamlessly update होते हुए।

Note: यह tradeoff (briefly possibly-outdated data दिखाना) आमतौर पर एक snappier UI के लिए एक अच्छा trade है — SWR इसे moments बाद automatically update कर देता है।
Warning: उस data के लिए जो always perfectly fresh होना चाहिए (जैसे एक live financial balance), brief staleness window acceptable नहीं हो सकता — उसी के according revalidation settings configure करें।

उदाहरण: The Stale-While-Revalidate Idea

markup
// Run in your local React project (npm install required)
import useSWR from 'swr';

const fetcher = url => fetch(url).then(res => res.json());

function UserList() {
  const { data, error, isLoading } = useSWR('/api/users', fetcher);
  if (isLoading) return <p>Loading...</p>;
  if (error) return <p>Failed to load</p>;
  return <ul>{data.map(u => <li key={u.id}>{u.name}</li>)}</ul>;
}

⚠️ This example uses an npm package with no CDN build available here — run this in your local React project.

Key और Fetcher Pattern

useSWR दो arguments लेता है: एक key (आमतौर पर URL, request को identify और cache करने के लिए उपयोग होता है) और एक fetcher function जो actually request perform करता है।

SWR में built-in fetcher include नहीं है — आप एक छोटा function देते हैं, अक्सर fetch() का बस एक thin wrapper।

Note: एक shared fetcher function एक बार define करें और अपने app में हर useSWR call में reuse करें।
Warning: key के रूप में null pass करना SWR को पूरी तरह fetching skip करने को कहता है — conditional fetching के लिए useful, लेकिन accidentally करना easy अगर एक variable unexpectedly null हो।

उदाहरण: The Key and Fetcher Pattern

markup
// Run in your local React project (npm install required)
import useSWR from 'swr';

const fetcher = url => fetch(url).then(res => res.json());

function Profile({ userId }) {
  const { data } = useSWR(userId ? `/api/users/${userId}` : null, fetcher);
  return <p>{data ? data.name : 'No user selected'}</p>;
}

⚠️ This example uses an npm package with no CDN build available here — run this in your local React project.

Automatic Background Revalidation

By default, SWR situations में automatically data refetch करता है जैसे browser window focus regain करना या network reconnect होना, बिना किसी manual refresh logic के data fresh रखते हुए।

ये behaviors एक third argument के रूप में pass किए गए configuration options के through tune किए जा सकते हैं।

Note: revalidateOnFocus उन dashboards के लिए खासकर useful है जिन्हें fresh data दिखाना चाहिए जब एक user tab पर वापस switch करे।
Warning: ये automatic background refetches अगर tune न किए जाएं तो expected से ज़्यादा network requests का कारण बन सकते हैं — अगर यह concern बने तो SWR के config options check करें।

उदाहरण: Automatic Background Revalidation

markup
// Run in your local React project (npm install required)
import useSWR from 'swr';

const fetcher = url => fetch(url).then(res => res.json());

function LiveData() {
  const { data } = useSWR('/api/stats', fetcher, {
    revalidateOnFocus: true,
    refreshInterval: 5000,
  });
  return <p>Stat value: {data?.value}</p>;
}

⚠️ This example uses an npm package with no CDN build available here — run this in your local React project.

Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. SWR की key को एक React Query query key syntax के साथ confuse करना — SWR की key आमतौर पर बस URL string ही होती है, एक array नहीं।
  2. stale-while-revalidate को न समझना — SWR intentionally पहले old cached data दिखाता है, फिर इसे update करता है, हमेशा एक fresh fetch पर block करने के बजाय।
  3. यह भूल जाना कि fetcher function built-in नहीं है — आपको एक खुद देना होगा (अक्सर एक simple fetch wrapper)।
चैप्टर सारांश
  • SWR stale-while-revalidate HTTP caching strategy के नाम पर एक lightweight data-fetching library है।
  • useSWR(key, fetcher) data, error, और isLoading return करता है, background में automatically refetch करते हुए।
  • key typically request URL ही होती है, जो हर request को identify और cache करने के लिए उपयोग होती है।
  • SWR cached (possibly stale) data तुरंत दिखाता है जबकि silently background में एक fresh copy fetch करता है।
ब्राउज़र सपोर्ट

npm install swr चाहिए — इस sandbox में CDN से उपलब्ध नहीं है; React 16.8+ के साथ काम करता है।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.