✨ Quick Answer: React mein useFetch custom hook kaise banayein? Is step-by-step guide se sikhein API fetching ko asaan aur reusable banana. Aaj hi start karein!
React me useFetch custom hook kaise banayein? Is step-by-step guide me hum API calls ko clean, reusable aur efficient banana seekhenge expert developers ki tarah.Dosto, jab hum ReactJS par kaam karte hain, toh har dusre component me API se data fetch karne ke liye hum baar-baar useEffect aur useState likhte hain. Kya aapko nahi lagta ki yeh ek redundant kaam hai? Ek senior developer ke taur par, main aapko wahi sikhaunga jo hum production level apps me karte hain: Custom Hooks ka use karna.
useFetch custom hook ek reusable logic hai jo API calls ko handle karta hai. Yeh useState aur useEffect ko wrap karke data, loading state, aur error handling ko automate karta hai, jisse aapka code cleaner aur maintainable banta hai.React me useFetch Custom Hook ki zaroorat kyun hai?
Jab aap ek hi project me 10 alag jagah data fetch karte hain, toh code me duplication badh jaati hai. Agar kal ko API ka response structure change hua, toh aapko 10 jagah code edit karna padega. Custom Hooks ka concept DRY (Don't Repeat Yourself) principle par chalta hai. Yeh hamare logic ko encapsulate kar deta hai.
useFetch Custom Hook Kaise Banayein (Step-by-Step)
Chaliye, ab code ki taraf badhte hain. Hum ek aisi file banayenge jo kisi bhi URL ko le sake aur result return kare.
Step 1: Custom Hook File create karein
Sabse pehle useFetch.js naam ki file banaiye:
import { useState, useEffect } from 'react';
const useFetch = (url) => {
const [data, setData] = useState(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const abortController = new AbortController();
const fetchData = async () => {
setIsLoading(true);
try {
const response = await fetch(url, { signal: abortController.signal });
if (!response.ok) throw Error('Could not fetch the data');
const json = await response.json();
setData(json);
setIsLoading(false);
setError(null);
} catch (err) {
if (err.name !== 'AbortError') {
setError(err.message);
setIsLoading(false);
}
}
};
fetchData();
return () => abortController.abort();
}, [url]);
return { data, isLoading, error };
};
export default useFetch;
Step 2: Component me Hook ka use kaise karein
Ab is hook ko apne kisi bhi component me use karna behad aasaan hai:
import useFetch from './useFetch';
const UserList = () => {
const { data, isLoading, error } = useFetch('https://jsonplaceholder.typicode.com/users');
if (isLoading) return Loading...;
if (error) return Error: {error};
return (
<ul>
{data.map(user => <li key={user.id}>{user.name}</li>)}
</ul>
);
};
useFetch Hook vs Standard useEffect Difference
| Feature | Standard useEffect | Custom useFetch Hook |
|---|---|---|
| Reusability | Low (code repetition) | High (write once) |
| Complexity | High (UI logic mixed) | Low (Clean Separation) |
| Maintenance | Hard | Easy |
Performance aur Best Practices
Dosto, yahan kuch baatein hain jo aapko Official React Docs ke hisaab se yaad rakhni chahiye:
- AbortController ka use: Maine upar diye gaye code me
AbortControllerka use kiya hai. Yeh tab kaam aata hai jab user component se jaldi navigate kar jaaye, jisse memory leak nahi hota. - Dependency Array: Hamesha
urlko dependency me rakhein taaki jab URL badle, toh data re-fetch ho. - Error Handling: API failure hone par UI crash na ho, isliye
try-catchblock zaroori hai.
Common Errors aur Debugging
Agar aapko koi error face ho rahi hai, toh sabse pehle ye check karein:
1. Kya URL sahi format me hai?
2. Kya AbortController handle kiya gaya hai?
3. Network tab me response status check karein.
Frequently Asked Questions (FAQs)
useFetch hook ko har jagah URL change karke use karein.useEffect ke andar koi variable use karte hain lekin usse dependency array me include nahi karte.Toh dosto, humne aaj seekha ki kaise useFetch custom hook bana kar hum apne code ko clean aur efficient bana sakte hain. Custom hooks sirf code ko chhota nahi karte, balki debugging ko bhi aasaan banate hain. Happy coding!


टिप्पणियाँ
एक टिप्पणी भेजें