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)
- A single
statusstate (avoid separate booleans that can contradict). - Start the request in an effect; abort it in cleanup.
- Check
res.ok, parse JSON, set data. - Catch errors (ignore
AbortError). - Provide
retryby bumping a counter in the dependency array.
Declarative version (Suspense + use)
- Create the promise outside render: in an event handler, a parent, a router loader, or a cache.
const data = use(promise)inside the child.<Suspense fallback={<Spinner />}>shows the loader.- 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-busyand 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";34type User = { id: number; firstName: string; email: string };56// 1) Imperative: explicit states + abort + retry7export 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);1011 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]);2021 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}2526// 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>;2829function UserCard({ userPromise }: { userPromise: Promise<User> }) {30 const user = use(userPromise);31 return <p>{user.firstName} ({user.email})</p>;32}3334export function UserSection() {35 const [promise, setPromise] = useState(() => fetchUser(1)); // created once, not during every render36 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.