Extracting Fetch Logic
You'll learn how to bundle all the messy parts of API calls—loading states, error handling, and data—into one reusable useFetch hook.
The Problem with Scattered Fetch Logic
Every time you fetch data in a component, you write the same boilerplate: a loading state, an error state, a data state, a useEffect to trigger the request, and error handling. Copy-pasting this across components is tedious and error-prone.
Building useFetch
A custom useFetch hook extracts all that repetitive logic into one place. It takes a URL, manages the three states internally, and returns them:
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
setLoading(true);
setError(null);
fetch(url)
.then(response => {
if (!response.ok) throw new Error('Network error');
return response.json();
})
.then(data => {
setData(data);
setLoading(false);
})
.catch(err => {
setError(err.message);
setLoading(false);
});
}, [url]);
return { data, loading, error };
}
Now in your component:
function UserProfile() {
const { data, loading, error } = useFetch('/api/user');
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error}</p>;
return <div>{data.name}</div>;
}
Why This Works
You've taken the pattern of fetching and turned it into a building block. Every component needing data follows the same three-state flow, but now you write it once and reuse it everywhere. Change how errors are handled? Update useFetch once, and all components benefit.
Key Takeaway: A useFetch custom hook centralizes loading, error, and data states for API calls, eliminating repetitive boilerplate and making data-fetching components cleaner and more consistent.