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.

In shortUse fetch inside useEffect with cleanup for small cases, or TanStack Query for real apps.

Theory in plain words

Request statesloadingsuccesserrorretry
Request states

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
fetch with loading, error and cleanupTry it Yourself

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.

TanStack Query
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 in
Careful:Never put an API secret key in React code. Everything in the browser bundle is public. Keep secrets on a server (for example a PHP endpoint on your hosting).

Quick quiz

1. Why abort or ignore old requests?

2. Where should an API secret key be stored?

3. Three states to handle?

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.