React API Fetching Explained — Data Fetching Patterns
DodaTech
Updated 2026-06-28
1 min read
In this tutorial, you will learn about React API Fetching Explained. We cover key concepts, practical examples, and best practices to help you master this topic.
React API fetching typically uses the native fetch API or axios inside useEffect, with additional libraries like React Query providing Caching, refetching, and state management.
What You'll Learn
- How to fetch data with useEffect and fetch
- How to handle loading, error, and empty states
- How to abort requests on unmount
- How to use React Query for data fetching
- How to build a custom useFetch hook
Why It Matters
Data fetching is the most common side effect in React apps. Doing it correctly prevents memory leaks, race conditions, and redundant requests.
function useFetch(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const controller = new AbortController();
setLoading(true);
fetch(url, { signal: controller.signal })
.then(r => { if (!r.ok) throw new Error("HTTP " + r.status); return r.json(); })
.then(d => { setData(d); setLoading(false); })
.catch(e => { if (e.name !== "AbortError") { setError(e.message); setLoading(false); } });
return () => controller.abort();
}, [url]);
return { data, loading, error };
}
function UsersList() {
const { data, loading, error } = useFetch("/api/users");
if (loading) return <p>Loading...</p>;
if (error) return <p>Error: {error}</p>;
return <ul>{data?.map(u => <li key={u.id}>{u.name}</li>)}</ul>;
}
Expected output: A user list that fetches data, shows loading, handles errors, and aborts on unmount.
← Previous
React Nested Routes Explained — Layouts and Sub-routes
Next →
React Axios Explained — HTTP Client for React Apps
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro