React › Custom Hooks
How would you write a custom hook to fetch data from an API and share that logic across components?
IntermediateAnswer
You move the fetching logic, along with loading and error state, inside a custom hook, and return whatever the component needs, such as the data, a loading flag, and any error. Every component that needs to fetch similar data can now reuse this one hook instead of repeating the same fetch code everywhere.
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
fetch(url)
.then((res) => res.json())
.then((json) => { setData(json); setLoading(false); });
}, [url]);
return { data, loading };
}
const { data, loading } = useFetch('/api/products');Real-world example A team building a dashboard reuses one useFetch custom hook across the users page, the orders page, and the reports page, avoiding writing the same fetch and loading logic three separate times.