How do you handle loading states during data fetching?

Use loading.tsx for route-level loading UI and <Suspense fallback> boundaries for individual slow components, so the page streams. For client interactions, use useTransition, useFormStatus, useActionState pending flags, useLinkStatus for links, or a data library's isLoading.

Server-rendered data

  • loading.tsx: an automatic <Suspense> boundary around a segment's page. Shows instantly on navigation.
  • <Suspense> around each slow component: the rest of the page renders while it waits. Several boundaries stream independently, so a slow widget never blocks the header.
  • Skeletons that match the final layout avoid layout shift.
  • With Cache Components, fallbacks become part of the static shell and can be prefetched, so the loading UI appears with no network wait.

Client-side state

  • Navigation: useLinkStatus() inside a <Link> shows a subtle pending indicator; useTransition around router.push.
  • Forms: useFormStatus() gives pending inside a <form>; useActionState returns isPending.
  • Optimistic UI: useOptimistic shows the expected result immediately.
  • Client fetching: SWR or TanStack Query provide isLoading and isFetching.

Good practice

  • Do not wrap the whole page in a single spinner; place boundaries around independent pieces.
  • Avoid flashes: very fast content does not need a fallback.
  • Announce loading to screen readers with aria-busy or aria-live.
  • Test in production mode or with the Navigation Inspector in DevTools; dev has no prefetching.

Code example

tsx
1// app/dashboard/page.tsx
2import { Suspense } from "react";
3import { Revenue, LatestInvoices, Cards } from "./widgets"; // async Server Components
4
5export default function Dashboard() {
6 return (
7 <main>
8 <h1>Dashboard</h1>
9 <Suspense fallback={<div className="h-24 animate-pulse bg-slate-200" />}>
10 <Cards />
11 </Suspense>
12 <div className="grid grid-cols-2 gap-4">
13 <Suspense fallback={<p>Loading revenue…</p>}>
14 <Revenue />
15 </Suspense>
16 <Suspense fallback={<p>Loading invoices…</p>}>
17 <LatestInvoices />
18 </Suspense>
19 </div>
20 </main>
21 );
22}
23
24// app/components/submit.tsx
25// "use client";
26// import { useFormStatus } from "react-dom";
27// export function Submit() {
28// const { pending } = useFormStatus();
29// return <button disabled={pending}>{pending ? "Saving…" : "Save"}</button>;
30// }

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 Next.js set.

Open in study app