A custom hook हा एक फंक्शन आहे ज्याचे नाव use ने सुरू होते आणि जो इतर hooks ला कॉल करतो stateful लॉजिक पॅकेज आणि पुन्हा वापरण्यासाठी — तुमच्या component tree ना बदलल्याशिवाय (HOCs किंवा render props प्रमाणे नाही)।
jsx
// extract "fetch + loading + error" logic once, reuse everywhere
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const ctrl = new AbortController();
setLoading(true);
fetch(url, { signal: ctrl.signal })
.then(r => r.json())
.then(setData)
.catch(e => { if (e.name !== "AbortError") setError(e); })
.finally(() => setLoading(false));
return () => ctrl.abort();
}, [url]);
return { data, loading, error };
}
// usage — the component stays declarative:
function Profile({ id }) {
const { data, loading, error } = useFetch(`/api/users/${id}`);
if (loading) return <Spinner />;
return <h1>{data.name}</h1>;
}
महत्वाचे गुणधर्म
- हे Rules of Hooks चे पालन करते (शीर्ष स्तरावर कॉल करा; फक्त components/hooks वरून)।
- State प्रत्येक कॉलसाठी अलग आहे।
useFetchवापरणार्या दोन components ला प्रत्येकी त्यांचे स्वतंत्र state मिळतात — hook शेअर करणे डेटा शेअर करत नाही। - संमेलन: त्याचे नाव
useXठेवा आणि state + functions परत करा (सहसा अ्रे किंवा object)।
हे का महत्वाचे आहे
Custom hooks हा आधुनिक React मध्ये लॉजिक शेअर करण्याचा प्रामाणिक मार्ग आहे (डेटा fetching, forms, subscriptions, media queries), components लहान ठेवून आणि लॉजिक अलग-अलग टेस्ट करण्यायोग्य बनवून।
