ReactMedium

How to fetch data?

Pick the approach by architecture: in frameworks, fetch on the server (Server Components, route loaders); in client-rendered apps, use a data library such as TanStack Query or SWR (or RTK Query with Redux); React 19's use(promise) with Suspense reads promises created outside render; and plain fetch in useEffect is the low-level fallback that needs careful handling.

Options

  1. Server-side (best first load): Next.js Server Components, React Router loaders. Data arrives with the HTML, no client waterfalls, secrets stay on the server.
  2. TanStack Query / SWR: caching, deduplication, background refetching, retries, pagination, optimistic updates and devtools. useQuery({ queryKey, queryFn }).
  3. use(promise) + <Suspense>: the promise must come from a cache, a parent, a loader or a library. Creating it inside the component would refetch every render.
  4. useEffect + fetch: fine for learning or tiny apps. You must handle loading, errors, race conditions (AbortController or an ignore flag), and Strict Mode double effects.

Good practices

  • Fetch in parallel (Promise.all, parallel loaders), not in nested waterfalls.
  • Cancel or ignore stale requests when inputs change.
  • Validate responses (Zod) at the boundary.
  • Show skeletons and error states with retry.
  • Cache and revalidate rather than refetching on every mount.
  • Prefetch on hover or in route loaders.
  • Keep server data out of global client stores; let the data library be the cache.

HTTP clients

Native fetch is enough for most apps; Axios, ky or ofetch add conveniences like interceptors and JSON defaults.

Code example

tsx
1import { useEffect, useState } from "react";
2import { useQuery } from "@tanstack/react-query";
3
4type Repo = { id: number; name: string; stargazers_count: number };
5
6// Recommended in client apps: TanStack Query
7export function TopRepos({ org }: { org: string }) {
8 const { data, isPending, error, refetch } = useQuery({
9 queryKey: ["repos", org],
10 queryFn: async ({ signal }): Promise<Repo[]> => {
11 const res = await fetch(`https://api.github.com/orgs/${org}/repos?sort=stars`, { signal });
12 if (!res.ok) throw new Error(`HTTP ${res.status}`);
13 return res.json();
14 },
15 staleTime: 60_000,
16 });
17
18 if (isPending) return <p>Loading…</p>;
19 if (error) return <p>Failed: {error.message} <button onClick={() => refetch()}>Retry</button></p>;
20 return <ul>{data.slice(0, 5).map((r) => <li key={r.id}>{r.name} ★{r.stargazers_count}</li>)}</ul>;
21}
22
23// Low-level fallback: useEffect with abort and error handling
24export function useJson<T>(url: string) {
25 const [state, setState] = useState<{ data?: T; error?: string; loading: boolean }>({ loading: true });
26 useEffect(() => {
27 const ctrl = new AbortController();
28 setState({ loading: true });
29 fetch(url, { signal: ctrl.signal })
30 .then((r) => (r.ok ? r.json() : Promise.reject(new Error(`HTTP ${r.status}`))))
31 .then((data: T) => setState({ data, loading: false }))
32 .catch((e) => e.name !== "AbortError" && setState({ error: e.message, loading: false }));
33 return () => ctrl.abort();
34 }, [url]);
35 return state;
36}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app