← Back to React Course | Chapter 6: Custom Hooks & Advanced Patterns | Lesson 2 of 10

useFetch Hook बनाना

एक useFetch hook एक helper जैसा है जो आपके लिए internet से information लेकर आता है, फिर आपको result एक note के साथ देता है कि क्या यह अभी भी loading है।
Syntax
markup
function useFetch(url) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  useEffect(() => {
    // fetch data, then setData(...) and setLoading(false)
  }, [url]);
  return { data, loading };
}

Why Wrap fetch() in a Hook

Data fetch करने के लिए typically तीन pieces of state चाहिए होते हैं: data खुद, क्या यह अभी भी loading है, और क्या एक error हुआ। हर component में जिसे data चाहिए इस trio को manually लिखना repetitive है।

एक useFetch hook तीनों concerns को एक reusable function में bundle करता है।

Note: जब भी आप same 'const [data, setData] = useState(); const [loading, setLoading] = useState(true);' pattern दो बार लिखें, इसे एक hook में extract करें।
Warning: एक generic useFetch simple cases के लिए fine है, लेकिन real apps के लिए React Query जैसी एक dedicated library caching और retries कहीं ज़्यादा robustly handle करती है।

उदाहरण: Why Wrap fetch() in a Hook

markup
<!DOCTYPE html>
<html>
<head>
  <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
  <div id="root"></div>
  <script type="text/babel">
function useFetch(url) {
  const [data, setData] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  React.useEffect(() => {
    setData({ message: "Loaded from " + url });
    setLoading(false);
  }, [url]);
  return { data, loading };
}
function App() {
  const { data, loading } = useFetch("/api/greeting");
  return <p>{loading ? "Loading..." : data.message}</p>;
}
ReactDOM.createRoot(document.getElementById('root')).render(<App />);
  </script>
</body>
</html>

Handling Loading and Error States

एक robust useFetch एक error state भी track करता है, ताकि component एक request fail होने पर crash करने के बजाय एक friendly message दिखा सके। Hook loading को वापस false पर set करता है और error store करता है चाहे fetch succeed हो या fail हो।

Note: हमेशा एक नए fetch की शुरुआत में loading और error दोनों reset करें, उस case में जब URL change हो और एक previous error अभी भी lingering हो।
Warning: fetch() rejections को catch करना भूल जाने का मतलब है कि एक failed network request एक visible error state के बजाय एक unhandled promise rejection produce करता है।

उदाहरण: Handling Loading and Error States

markup
<!DOCTYPE html>
<html>
<head>
  <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
  <div id="root"></div>
  <script type="text/babel">
function useFetch(shouldFail) {
  const [error, setError] = React.useState(null);
  const [loading, setLoading] = React.useState(true);
  React.useEffect(() => {
    if (shouldFail) setError("Network error");
    setLoading(false);
  }, [shouldFail]);
  return { error, loading };
}
function App() {
  const { error, loading } = useFetch(true);
  if (loading) return <p>Loading...</p>;
  return <p style={{color: "red"}}>{error ? "Error: " + error : "Success"}</p>;
}
ReactDOM.createRoot(document.getElementById('root')).render(<App />);
  </script>
</body>
</html>

Avoiding State Updates After Unmount

अगर एक component इसका fetch खत्म होने से पहले unmount हो जाए, बाद में setState call करना एक React warning trigger करता है और एक memory leak mask कर सकता है। useEffect के return function के अंदर एक cleanup flag component के चले जाने पर state update skip करके इसे रोकता है।

Note: एक simple boolean flag उपयोग करें (जैसे cancelled) fetch को खुद abort करने की कोशिश करने के बजाय, जब तक आपको specifically AbortController न चाहिए।
Warning: इस cleanup check के बिना, useFetch उपयोग करने वाले pages के बीच rapidly switch करना unmounted components को update करने के बारे में console warnings produce कर सकता है।

उदाहरण: Avoiding State Updates After Unmount

markup
<!DOCTYPE html>
<html>
<head>
  <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
  <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>
  <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
</head>
<body>
  <div id="root"></div>
  <script type="text/babel">
function useSafeFetch(value) {
  const [result, setResult] = React.useState(null);
  React.useEffect(() => {
    let cancelled = false;
    setTimeout(() => { if (!cancelled) setResult(value); }, 0);
    return () => { cancelled = true; };
  }, [value]);
  return result;
}
function App() {
  const result = useSafeFetch("Safe data");
  return <p>{result || "Loading..."}</p>;
}
ReactDOM.createRoot(document.getElementById('root')).render(<App />);
  </script>
</body>
</html>
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 state handle करना भूल जाना, तो request in flight रहते UI कुछ नहीं (या stale data) दिखाता है।
  2. Component unmount होने पर fetch cancel न करना, जो एक 'state update on unmounted component' warning cause कर सकता है।
  3. हर render पर fetch फिर से run करना क्योंकि URL या dependency array correctly stabilized नहीं था।
चैप्टर सारांश
  • useFetch एक custom hook pattern है जो fetch() को loading/error state के साथ एक reusable hook में wrap करता है।
  • यह data, loading, और error return करता है ताकि कोई भी component हर state के लिए सही UI render कर सके।
  • Fetch useEffect के अंदर run होता है, URL dependency array में, तो URL change होने पर यह re-fetch करता है।
  • एक cleanup flag component unmount होने के बाद state updates रोकता है।
ब्राउज़र सपोर्ट

React 16.8 (Hooks introduction) से available है; standard fetch() API पर depend करता है, जो सभी modern evergreen browsers में supported है।

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.