Home / Learn React / Fetching Data
Fetching Data
Most apps load data from an API. You must handle three states: loading, error and success. Libraries such as TanStack Query handle caching and retries for you.
Theory in plain words
What it is
Data fetching means asking a server for data and showing it. In React the request is a side effect, so it is run in an effect, an event handler, a router loader, or a data library.
Why we use it
Naive fetching causes flicker, double requests and race conditions (an older response arriving last). Doing it carefully gives fast, reliable screens.
How it works
The component keeps data, loading and error. The effect starts the request and a cleanup ignores or aborts it if the component changes or unmounts.
Where it is used
- Lists, details, search, dashboards, any app with a backend
Click quickly between buttons: the cleanup cancels the old request so a stale answer never overwrites a new one. User 3 shows the error path.
npm install @tanstack/react-query
const { data, isPending, error } = useQuery({
queryKey: ["user", id],
queryFn: () => fetch("/api/users/" + id).then(r => r.json()),
});
// caching, retries, refetch on focus and de-duplication are built inQuick quiz
1. Why abort or ignore old requests?
Prevents race conditions.
2. Where should an API secret key be stored?
Browser code is public.
3. Three states to handle?
Always show all three.
Common questions
Why abort or ignore old requests?
To avoid stale responses overwriting new data. Prevents race conditions.
Where should an API secret key be stored?
On a server. Browser code is public.
Three states to handle?
loading, error, success. Always show all three.