Next.jsEasy
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;useTransitionaroundrouter.push. - Forms:
useFormStatus()givespendinginside a<form>;useActionStatereturnsisPending. - Optimistic UI:
useOptimisticshows the expected result immediately. - Client fetching: SWR or TanStack Query provide
isLoadingandisFetching.
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-busyoraria-live. - Test in production mode or with the Navigation Inspector in DevTools; dev has no prefetching.
Code example
tsx
1// app/dashboard/page.tsx2import { Suspense } from "react";3import { Revenue, LatestInvoices, Cards } from "./widgets"; // async Server Components45export 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}2324// app/components/submit.tsx25// "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.