Skip to main content
Albero Academy

Data Fetching Patterns

Load remote data reliably — loading and error states, avoiding race conditions and leaks, and why a data library often beats useEffect.

Chapter 12React16 min readBeginner friendly
  • #React
  • #Data Fetching
  • #Async

Almost every app loads data from a server. Doing it robustly means handling more than the happy path — loading indicators, errors, and the subtle bugs (race conditions, updates after unmount) that catch beginners. This chapter is the reliable pattern, and when to stop hand-rolling it.

The three states

Every fetch is really three UI states you must handle: loading, error, and success.

Fetching in an effect

the basic pattern
function Students() {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
fetch("/api/students")
.then(res => { if (!res.ok) throw new Error("HTTP " + res.status); return res.json(); })
.then(setData)
.catch(setError)
.finally(() => setLoading(false));
}, []);
if (loading) return <Spinner />;
if (error) return <p>Failed to load.</p>;
return <ul>{data.map(s => <li key={s.id}>{s.name}</li>)}</ul>;
}

Race conditions & cleanup

safe fetching
useEffect(() => {
let active = true;
fetch(`/api/search?q=${query}`)
.then(r => r.json())
.then(json => { if (active) setResults(json); }); // ignore if stale
return () => { active = false; }; // cleanup on unmount / next run
}, [query]);

A reusable useFetch

Wrap the pattern in a custom hook so components stay clean:

useFetch
function useFetch(url) {
const [state, setState] = useState({ data: null, loading: true, error: null });
useEffect(() => {
let active = true;
setState({ data: null, loading: true, error: null });
fetch(url)
.then(r => r.json())
.then(data => active && setState({ data, loading: false, error: null }))
.catch(error => active && setState({ data: null, loading: false, error }));
return () => { active = false; };
}, [url]);
return state;
}
// const { data, loading, error } = useFetch("/api/students");

Why a data library

Hand-rolled fetching quickly needs caching, refetching, deduping and background updates. Libraries like TanStack Query (React Query) or SWR give you all of that in a one-line hook. For anything beyond a couple of simple loads, they're the pragmatic default — you write less code and get more reliability.

Practice

Build a search box that fetches results as the query changes — and fix the race condition with the active flag. Extract a useFetch hook returning { data, loading, error } and use it in two components.

Key takeaways

  1. 01Handle all three states: loading, error, success.
  2. 02Fetch in useEffect; throw on !res.ok and set state in then/catch/finally.
  3. 03Guard against race conditions and post-unmount updates with a cleanup flag or AbortController.
  4. 04Wrap the pattern in a useFetch hook to keep components clean.
  5. 05For real apps, use TanStack Query / SWR — caching, refetching and dedup out of the box.