Custom React Hook for Reusable Data Fetching

If you're copying and pasting the same useState + useEffect logic across multiple components, you need a custom hook. Example — a reusable data fetching hook: ```js function useFetch(url) { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { let cancelled = false; fetch(url) .then(r => r.json()) .then(data => { if (!cancelled) setData(data); }) .catch(err => { if (!cancelled) setError(err); }) .finally(() => { if (!cancelled) setLoading(false); }); return () => { cancelled = true; }; }, [url]); return { data, loading, error }; } // Usage — clean and consistent everywhere const { data: users, loading } = useFetch('/api/users'); const { data: products } = useFetch('/api/products'); ``` Custom hooks keep components focused on rendering and move logic to where it can be tested and reused. #ReactJS #JavaScript #Frontend #WebDevelopment

To view or add a comment, sign in

Explore content categories