ReactMedium

API fetch + loader

Fetching with a loader means representing the request as explicit states (idle, loading, success, error), showing a spinner or skeleton while loading, rendering data on success, and showing an error with a retry button on failure. In React 19 you can also express it declaratively: pass a promise to a component that reads it with use(), with <Suspense> providing the loader and an error boundary handling failures.

Imperative version (useEffect)

  1. A single status state (avoid separate booleans that can contradict).
  2. Start the request in an effect; abort it in cleanup.
  3. Check res.ok, parse JSON, set data.
  4. Catch errors (ignore AbortError).
  5. Provide retry by bumping a counter in the dependency array.

Declarative version (Suspense + use)

  1. Create the promise outside render: in an event handler, a parent, a router loader, or a cache.
  2. const data = use(promise) inside the child.
  3. <Suspense fallback={<Spinner />}> shows the loader.
  4. An error boundary renders the failure UI; resetting it with a new promise retries.

Good loading UX

  • Skeletons matching the final layout.
  • Avoid flashing spinners for very fast responses.
  • Keep old data visible when refreshing.
  • Announce state changes with aria-busy and live regions.

In production

TanStack Query or SWR handle caching, retries and deduplication; React Router loaders and Server Components load data before render.

Code example

tsx
1import { Suspense, use, useEffect, useState } from "react";
2import { ErrorBoundary } from "react-error-boundary";
3
4type User = { id: number; firstName: string; email: string };
5
6// 1) Imperative: explicit states + abort + retry
7export function UserCardEffect({ id }: { id: number }) {
8 const [state, setState] = useState<{ status: "loading" | "success" | "error"; user?: User; error?: string }>({ status: "loading" });
9 const [attempt, setAttempt] = useState(0);
10
11 useEffect(() => {
12 const ctrl = new AbortController();
13 setState({ status: "loading" });
14 fetch(`https://dummyjson.com/users/${id}`, { signal: ctrl.signal })
15 .then((r) => (r.ok ? r.json() : Promise.reject(new Error(`HTTP ${r.status}`))))
16 .then((user: User) => setState({ status: "success", user }))
17 .catch((e) => e.name !== "AbortError" && setState({ status: "error", error: e.message }));
18 return () => ctrl.abort();
19 }, [id, attempt]);
20
21 if (state.status === "loading") return <p aria-busy="true">Loading user…</p>;
22 if (state.status === "error") return <p role="alert">{state.error} <button onClick={() => setAttempt((a) => a + 1)}>Retry</button></p>;
23 return <p>{state.user!.firstName} ({state.user!.email})</p>;
24}
25
26// 2) Declarative: use() + Suspense + error boundary (React 19)
27const fetchUser = (id: number) => fetch(`https://dummyjson.com/users/${id}`).then((r) => (r.ok ? r.json() : Promise.reject(new Error("Failed")))) as Promise<User>;
28
29function UserCard({ userPromise }: { userPromise: Promise<User> }) {
30 const user = use(userPromise);
31 return <p>{user.firstName} ({user.email})</p>;
32}
33
34export function UserSection() {
35 const [promise, setPromise] = useState(() => fetchUser(1)); // created once, not during every render
36 return (
37 <ErrorBoundary fallbackRender={({ resetErrorBoundary }) => <button onClick={() => { setPromise(fetchUser(1)); resetErrorBoundary(); }}>Retry</button>}>
38 <Suspense fallback={<p>Loading user…</p>}><UserCard userPromise={promise} /></Suspense>
39 </ErrorBoundary>
40 );
41}

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