ReactEasy

Loading states?

Loading states tell users that something is happening. Show them close to the content that is loading, prefer skeletons that match the final layout over full-page spinners, avoid flashes for very fast loads, keep old content visible while refreshing, and drive them from the data layer (isPending from TanStack Query, <Suspense> fallbacks, useTransition's isPending, useFormStatus).

Patterns

  • Initial load: skeletons or placeholders with the same size as the content, to prevent layout shift.
  • Refetching or pagination: keep showing the previous data with a subtle indicator (TanStack Query's placeholderData: keepPreviousData, isFetching).
  • Navigation: keep the current page and show a progress bar (useNavigation().state in React Router, transitions).
  • Mutations: disable the submit button and show "Saving…" (useFormStatus, useActionState's isPending), or update optimistically with useOptimistic.
  • Suspense: declarative fallbacks per region, revealed progressively.

Avoid

  • A spinner replacing the whole page for a small refresh.
  • Flashing a spinner for 50ms: delay showing it (around 200ms) or rely on transitions, which keep old UI until new content is ready.
  • Several independent boolean flags; use one status value (idle | loading | success | error).

Accessibility

  • aria-busy="true" on the loading region.
  • Announce completion or errors in a live region when appropriate.
  • Respect prefers-reduced-motion for skeleton shimmer animations.

Code example

tsx
1import { Suspense } from "react";
2import { keepPreviousData, useQuery } from "@tanstack/react-query";
3
4function Skeleton({ rows = 3 }: { rows?: number }) {
5 return (
6 <ul aria-busy="true" aria-label="Loading">
7 {Array.from({ length: rows }, (_, i) => <li key={i} className="h-5 w-full animate-pulse rounded bg-slate-200 motion-reduce:animate-none" />)}
8 </ul>
9 );
10}
11
12export function Orders({ page }: { page: number }) {
13 const { data, isPending, isFetching } = useQuery({
14 queryKey: ["orders", page],
15 queryFn: () => fetch(`/api/orders?page=${page}`).then((r) => r.json() as Promise<{ id: string; total: number }[]>),
16 placeholderData: keepPreviousData, // keep old page visible while the next one loads
17 });
18
19 if (isPending) return <Skeleton />; // first load only
20 return (
21 <section style={{ opacity: isFetching ? 0.6 : 1 }}>
22 {data.map((o) => <p key={o.id}>#{o.id}: ${o.total}</p>)}
23 </section>
24 );
25}
26
27// Suspense-style: declarative fallback per region
28// <Suspense fallback={<Skeleton rows={5} />}><Comments /></Suspense>
29export { Suspense };

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