By : cs
Language: javascript
Date Published: 2 weeks, 3 days ago
React custom hooks help separate data fetching logic from UI components, keeping them clean and reusable.
Custom hooks are just normal JavaScript functions that use React’s built-in hooks (useState, useEffect) internally.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | import { useState, useEffect } from 'react'; /** * Custom hook to fetch data from an API endpoint. */ export const useFetch = (url) => { const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { let ignore = false; async function fetchData() { try { const response = await fetch(url); if (!response.ok) throw new Error('Network response was not ok'); const result = await response.json(); if (!ignore) setData(result); } catch (err) { setError(err.message); } finally { setLoading(false); } } fetchData(); return () => { ignore = true }; // cleanup on unmount }, [url]); return { data, loading, error }; }; |