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

React Query का परिचय

React Query एक smart librarian जैसा है जो याद रखता है कि आप कौन सी books पहले ही borrow कर चुके हैं, इसलिए आपको हर बार same book मांगने पर shelf तक वापस जाना नहीं पड़ता।
Syntax
markup
const queryClient = new QueryClient();

<QueryClientProvider client={queryClient}>
  <App />
</QueryClientProvider>

const { data, isLoading, error } = useQuery({
  queryKey: ["key", id],
  queryFn: fetchFunction,
});

Manual fetch + useState के बजाय React Query क्यों

useState और useEffect से manually data fetch करने का मतलब है हर बार अपनी loading/error/caching logic लिखना। React Query यह सब automatically handle करता है — results cache करना, duplicate requests avoid करना, और data stale होने पर refetch करना — एक simple hook के पीछे।

Note: React Query खासकर उस data के लिए shine करता है जो कई components को चाहिए, या जिसे समय के साथ automatically refresh होना चाहिए।
Warning: यह specifically SERVER state (एक API से data) के लिए है — यह local UI state जैसे form inputs या modal visibility को replace करने के लिए नहीं है।

उदाहरण: Why React Query Instead of Manual fetch + useState

markup
// Run in your local React project (npm install required)
import { useQuery } from '@tanstack/react-query';

function UserList() {
  const { data, isLoading, error } = useQuery({
    queryKey: ['users'],
    queryFn: () => fetch('/api/users').then(res => res.json()),
  });
  if (isLoading) return <p>Loading...</p>;
  if (error) return <p>Error loading users</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.

QueryClientProvider Set Up करना

React Query को एक QueryClient instance चाहिए जो एक बार बनाया जाए और QueryClientProvider के through पूरे app को दिया जाए, Redux के Provider जैसा। यह client shared cache manage करता है जो app में हर useQuery call इससे पढ़ता और लिखता है।

Note: QueryClient को module scope पर एक बार बनाएं, किसी component के अंदर नहीं, ताकि यह हर render पर recreate न हो।
Warning: useQuery call करने वाले किसी भी component को QueryClientProvider के अंदर render होना चाहिए, नहीं तो यह error throw करेगा।

उदाहरण: Setting Up the QueryClientProvider

markup
// Run in your local React project (npm install required)
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

const queryClient = new QueryClient();

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <UserList />
    </QueryClientProvider>
  );
}

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

Query Keys को समझना

एक query key (एक array, जैसे [users] या [user, userId]) cached data के एक piece को uniquely identify करती है। React Query इसे decide करने के लिए उपयोग करता है कि data मांगने वाले दो components SAME चीज़ मांग रहे हैं (एक cache entry share करते हुए) या अलग चीज़ें (separate entries)।

Note: Query के depend करने वाली किसी भी variable को directly key में include करें, जैसे [user, userId], ताकि userId बदलने पर React Query automatically refetch करे।
Warning: genuinely अलग data के लिए same query key दोहराना React Query को गलत cache entry से stale, mismatched data serve कराता है।

उदाहरण: Understanding Query Keys

markup
// Run in your local React project (npm install required)
import { useQuery } from '@tanstack/react-query';

function UserDetail({ userId }) {
  const { data } = useQuery({
    queryKey: ['user', userId],
    queryFn: () => fetch(`/api/users/${userId}`).then(r => r.json()),
  });
  return <p>{data?.name}</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. Loading/error/data state को manually React Query के साथ manage करना जब library already useQuery के return value के through यह सब provide करती है।
  2. दो unrelated queries को exact same query key देना, जो उन्हें incorrectly cached data share करने का कारण बनता है।
  3. App को एक QueryClientProvider में wrap करना भूल जाना, जो useQuery को चाहिए।
चैप्टर सारांश
  • React Query (अब TanStack Query) server-state manage करता है: remote data fetch, cache, और synchronize करना।
  • useQuery(key, fetchFn) बिना manual state management के automatically data, isLoading, और error return करता है।
  • एक unique query key हर cached query को identify करती है, automatic caching और refetching enable करते हुए।
  • useQuery को tree में कहीं भी काम करने के लिए app को एक QueryClientProvider में wrap होना चाहिए।
ब्राउज़र सपोर्ट

npm install @tanstack/react-query चाहिए — इस 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.