Loaders
Loading indicator patterns — top-of-page progress bars, skeleton screens, spinners, and when to use which.
When to use what
Not every wait needs a loader. The time thresholds below come from Miller (1968), Card, Moran & Newell (1983), and Nielsen (1993) — the indicator recommendations are common UX practice informed by those limits:
| Wait time | Recommended indicator |
|---|---|
| < 1 second | Nothing — instant feel |
| 1–3 seconds | Spinner or subtle indicator |
| 2–10 seconds | Skeleton screen or progress bar |
| > 10 seconds | Determinate progress bar with time estimate |
Where to put it
No study compares a spinner in the button with a shared indicator elsewhere directly. The nearby evidence agrees: put the feedback where the person is looking.
- In a reaching experiment, people responded faster when feedback appeared where they were acting rather than at another location (Psychological Research, 2018).
- In an eye-tracking study of form errors, messages right next to the field were spotted fastest, though some measures weren't statistically significant (Inal, 2016).
- NN/g: the system should show at once that it received the request — "Without any visual change from the system, most users will assume the action was not registered and they will try again" (Sherwin, 2014).
- Apple: "Display a progress indicator in a consistent location", and spinners work "next to a specific control, such as a button" (HIG: Progress indicators).
| What's loading | Where |
|---|---|
| Result of one control (save, submit, add to cart) | On or next to that control |
| The whole page or route (navigation) | One shared, consistent place — the top progress bar |
| Many parts at once (a dashboard, a grid of cards) | One shared indicator, not a spinner per card |
| Background refresh of content already on screen | Small, next to that content |
They combine: the button shows it's working while the request runs, and if the result is a new page, the top bar takes over for the navigation. What to avoid is a click whose only feedback is a top bar far from the button — it's outside the user's focus, gets missed, and they click again.
A spinner drawn inside a button isn't announced by screen readers. Pair it with a text change ("Saving…") or a status message (see Announcements).
Top-of-page progress bar
A thin bar fixed to the top of the viewport that animates during navigation. YouTube (red), GitHub (blue), and many SPAs use this pattern. The bar gives a feeling of progress even though the percentage is fabricated — it trickles forward with easing and snaps to 100% when the page actually loads.
This pattern is specifically for page transitions — it should start when a route change begins and finish when the new page renders. It is not a good fit for general-purpose "something is loading" indicators. For background data fetching (e.g. TanStack Query's background fetching indicators), a subtle inline spinner near the stale content is a better choice — it tells the user what is refreshing, not just that something is happening.
Start the bar, wait, then finish it: fast start, slow crawl, and a snap to 100% that fades out.
The animation has three phases:
- Fast start — jumps to ~30% quickly (ease-out), giving immediate feedback.
- Slow crawl — creeps from 30% to 90% over several seconds (ease-in), buying time for the actual load.
- Instant finish — snaps to 100% and fades out when the page is ready.
All three phases are CSS-only. JavaScript only toggles a data-state
attribute between idle, loading, and done.
The non-linear easing is the key UX trick — a detailed analysis from Logto explains why GitHub's bar feels fast: the rapid initial movement creates a sense of momentum, while the slow middle avoids the jarring stall at 99% that linear progress bars produce.
Install with the shadcn CLI, or copy the source below. The keyframes ship
inside the component in a React 19 <style href precedence>: React moves it
into <head> once, however many bars render, so there is nothing to add to
your CSS.
npx shadcn@latest add https://ui-patterns.stereobooster.com/r/top-progress-bar.json"use client";
import * as React from "react";
import { cn } from "@/lib/utils";
type ProgressState = "idle" | "loading" | "done";
const KEYFRAMES = `
@keyframes progress-trickle {
0% { width: 0%; animation-timing-function: cubic-bezier(0.1, 0.8, 0.3, 1); }
8% { width: 30%; animation-timing-function: cubic-bezier(0.4, 0, 0.2, 1); }
50% { width: 60%; animation-timing-function: cubic-bezier(0.5, 0, 0.3, 1); }
100% { width: 90%; }
}
@keyframes progress-fade-out {
0%, 40% { width: 100%; opacity: 1; }
100% { width: 100%; opacity: 0; }
}
`;
interface TopProgressBarProps extends React.ComponentProps<"div"> {
loading: boolean;
}
function TopProgressBar({ loading, className, ...props }: TopProgressBarProps) {
const [state, setState] = React.useState<ProgressState>(
loading ? "loading" : "idle",
);
const [wasLoading, setWasLoading] = React.useState(loading);
if (loading !== wasLoading) {
setWasLoading(loading);
setState(loading ? "loading" : "done");
}
return (
<div
data-slot="top-progress-bar"
data-state={state}
aria-hidden="true"
onAnimationEnd={(event) => {
if (event.animationName === "progress-fade-out") setState("idle");
}}
className={cn(
"bg-primary pointer-events-none fixed top-0 left-0 z-50 h-0.5 w-0",
"data-[state=loading]:[animation:progress-trickle_8s_both]",
"data-[state=done]:[animation:progress-fade-out_0.4s_ease-out_both]",
className,
)}
{...props}
>
<style href="top-progress-bar" precedence="medium">
{KEYFRAMES}
</style>
<div className="from-primary/60 absolute top-0 right-0 h-full w-20 bg-gradient-to-l to-transparent opacity-0 transition-opacity duration-200 [[data-state=loading]_&]:opacity-100" />
</div>
);
}
export { TopProgressBar, type TopProgressBarProps };Usage: the bar only needs to know whether a navigation is pending. With
the Next.js App Router, start navigations in a transition and pass its
isPending:
const router = useRouter();
const [isPending, startTransition] = useTransition();
<TopProgressBar loading={isPending} />
<button onClick={() => startTransition(() => router.push("/reports"))}>
Reports
</button>The bar is aria-hidden: it's a visual cue, and the page change itself is
announced (Next.js has a built-in route announcer).
The per-keyframe animation-timing-function is what creates the
non-linear feel. Each segment of the animation uses a different
cubic-bezier curve, so the bar accelerates and decelerates within a
single @keyframes rule — no JavaScript timers needed.
Libraries
@bprogress/next (~700 stars,
active) — a TypeScript progress bar with first-class Next.js support (App
Router and Pages Router). Successor to the deprecated
next-nprogress-bar.
nextjs-toploader (~1.2k stars, active) — another drop-in component for Next.js.
@tanem/react-nprogress (~465 stars, active) — headless. Provides hooks and render props without any markup — you control the DOM entirely.
Pace.js (~15.6k stars) — framework- agnostic, automatically monitors Ajax requests, event loop lag, and document ready state. No manual start/done calls needed. Ships with 14+ themes. Less common in React projects because the automatic interception doesn't align well with React's data-fetching model.
Skeleton screens
Placeholder shapes that mirror the layout of the incoming content. They prevent layout shift and give the user a preview of what's coming.
Libraries
react-content-loader
(~14k stars, ~672k weekly downloads) — SVG-based. You compose <rect> and
<circle> elements inside a <ContentLoader> wrapper. An animated
gradient provides the shimmer. Less than 2 kB, zero deps. Has a visual
editor at skeletonreact.com where you can
draw skeletons and export code:
import ContentLoader from "react-content-loader";
function CardSkeleton() {
return (
<ContentLoader viewBox="0 0 400 160">
<rect x="0" y="0" rx="4" ry="4" width="400" height="100" />
<rect x="0" y="116" rx="3" ry="3" width="250" height="16" />
<rect x="0" y="140" rx="3" ry="3" width="180" height="12" />
</ContentLoader>
);
}react-loading-skeleton (~4.2k stars, ~930k weekly downloads) — DOM-based, simpler API:
import Skeleton from "react-loading-skeleton";
import "react-loading-skeleton/dist/skeleton.css";
function ProfileSkeleton() {
return (
<div>
<Skeleton circle width={48} height={48} />
<Skeleton count={3} />
</div>
);
}shadcn/ui Skeleton — a Tailwind animate-pulse div. No library
needed, just copy the component:
function Skeleton({ className, ...props }: React.ComponentProps<"div">) {
return (
<div
className={cn("animate-pulse rounded-md bg-muted", className)}
{...props}
/>
);
}CSS-only shimmer
The core technique without any library:
.skeleton {
background: linear-gradient(90deg, #e0e0e0 25%, #f0f0f0 50%, #e0e0e0 75%);
background-size: 200% 100%;
animation: shimmer 1.5s infinite linear;
border-radius: 4px;
}
@keyframes shimmer {
0% {
background-position: 200% 0;
}
100% {
background-position: -200% 0;
}
}Add background-attachment: fixed to synchronize the shimmer wave across
all skeleton elements on the page.
Best practices
- Match the layout — skeleton shapes should mirror actual content to prevent CLS (Cumulative Layout Shift).
- Skip short waits — a flash of skeleton is worse than no indicator. Delay it, and keep it up for a minimum time once shown — see Delayed indicators.
- Keep it subtle — pulse or shimmer, not bouncing or spinning.
- Accessibility — add
aria-busy="true"on the container andaria-labeldescribing what's loading.
Spinners
Best for small, localized loading — button actions, inline fetches, component-level states.
A CSS-only spinner in one element:
.spinner {
width: 24px;
height: 24px;
border: 3px solid #e0e0e0;
border-top-color: #3b82f6;
border-radius: 50%;
animation: spin 0.6s linear infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}CSS spinner collections:
- cssloaders.github.io — large collection of single-element CSS loaders
- css-loaders.com — 600+ CSS loading animations
- SpinKit by Tobias Ahlin — classic set of CSS spinners
Delayed indicators
Showing a spinner the moment a request starts looks responsive, but most requests are fast. If the response arrives in 150 ms, the user sees a spinner blink on and off — a visual glitch, not feedback. Two rules fix it:
- Delay — don't show the indicator until the wait has lasted a while. Fast responses then show nothing at all.
- Minimum duration — once the indicator is visible, keep it up for a minimum time. Otherwise a response that lands just after the delay (550 ms with a 500 ms delay) flashes the spinner for 50 ms — the same glitch, moved later.
Install with the shadcn CLI, or copy the source below.
npx shadcn@latest add https://ui-patterns.stereobooster.com/r/use-delayed-pending.json"use client";
import * as React from "react";
/**
* Turns a raw `pending` flag into "should the loading indicator be visible".
* The indicator appears only once `pending` has lasted `delay` ms, and once
* visible it stays for at least `minDuration` ms — so fast responses show
* nothing and borderline ones don't flash.
*/
export function useDelayedPending(
pending: boolean,
{
delay = 500,
minDuration = 200,
}: { delay?: number; minDuration?: number } = {},
) {
const [visible, setVisible] = React.useState(false);
const shownAt = React.useRef(0);
React.useEffect(() => {
if (pending && !visible) {
const timer = setTimeout(() => {
shownAt.current = performance.now();
setVisible(true);
}, delay);
return () => clearTimeout(timer);
}
if (!pending && visible) {
const elapsed = performance.now() - shownAt.current;
const timer = setTimeout(
() => setVisible(false),
Math.max(0, minDuration - elapsed),
);
return () => clearTimeout(timer);
}
}, [pending, visible, delay, minDuration]);
return visible;
}Usage:
const [isPending, startTransition] = useTransition();
const showSpinner = useDelayedPending(isPending);
<button disabled={isPending}>
Save {showSpinner && <Spinner aria-hidden />}
</button>
<p role="status" className="sr-only">
{showSpinner ? "Saving…" : ""}
</p>Notes:
- The numbers are convention, not research. The response-time limits above say a reaction under ~0.1 s feels instant and under ~1 s keeps the user's flow, which supports showing nothing for short waits. There is no study behind a specific delay or minimum. The defaults here are spin-delay's — a 500 ms delay and a 200 ms minimum — the most widely used implementation. Tune them with the sliders: a longer delay hides more fast responses but leaves slow ones without feedback for longer.
- Disable the control immediately, delay only the indicator. In the
usage example the button is disabled as soon as
isPendingis true — that prevents double submits without any visual flash. The spinner is the only thing that waits. - The minimum makes slow responses slightly slower. With a 200 ms minimum, a response at 550 ms isn't shown until 700 ms. That's the trade: a little latency in exchange for no flicker.
- Announce the delayed state, not the raw one. Screen reader users get
the same flicker otherwise. Keep the spinner itself
aria-hiddenand put the text in a status region that is always rendered — a spinner withrole="status"mounted on demand is usually not announced at all (see Announcements). - Same rule for skeletons and progress bars. Anything that appears for a loading state and disappears when it ends can flash.
- React experimented with this. The experimental Suspense config had
busyDelayMsandbusyMinDurationMsoptions (experimental types). The config was dropped before the stable release (commit removingtimeoutMs), and stableuseTransitiontakes no options — so a hook like this one fills the gap. - Server rendering. If a page renders while already pending, the
indicator starts hidden and appears after
delayon the client.spin-delayhas anssroption to show it immediately instead.
React patterns
useTransition + isPending
Wrapping a state update in startTransition lets the current UI stay
interactive while React renders the new state in the background:
const [isPending, startTransition] = useTransition();
function handleFilter(value: string) {
startTransition(() => {
setFilter(value);
});
}
return (
<button disabled={isPending}>{isPending ? "Filtering…" : "Apply"}</button>
);Suspense boundaries
Wrap async components in <Suspense> with a fallback. Use multiple
granular boundaries so each section streams in independently:
<Suspense fallback={<HeaderSkeleton />}>
<Header />
</Suspense>
<Suspense fallback={<FeedSkeleton />}>
<Feed />
</Suspense>
<Suspense fallback={<SidebarSkeleton />}>
<Sidebar />
</Suspense>Next.js loading.tsx
Place a loading.tsx alongside your page.tsx. Next.js automatically
wraps the page in a <Suspense> boundary with your loading component as
the fallback:
app/
dashboard/
page.tsx ← async page
loading.tsx ← shown instantly while page resolves// app/dashboard/loading.tsx
export default function Loading() {
return <DashboardSkeleton />;
}The loading UI is prefetched on link hover, so navigations feel instant.
Optimistic UI
Instead of showing a loader, update the UI immediately and assume the
server will succeed. React 19 provides useOptimistic for this:
const [optimisticMessages, addOptimistic] = useOptimistic(
messages,
(state, newMsg: string) => [...state, { text: newMsg, pending: true }],
);Best for idempotent, high-success-rate operations — likes, toggles, adding items to a list. Not appropriate for payments or destructive actions.
Further reading
Academic research
-
Miller (1968) — "Response time in man-computer conversational transactions" — the original 0.1 s / 1 s / 10 s response-time limits.
-
Card, Moran & Newell (1983) — The Psychology of Human-Computer Interaction — formalized the response-time thresholds into a cognitive model.
-
Harrison, Yeo & Hudson (2010) — "Faster Progress Bars" — visual augmentations (ribbing, deceleration) reduce perceived duration by ~11%. CHI '10.
-
Mejtoft, Langstrom & Soderstrom (2018) — "The effect of skeleton screens" — skeleton screens scored higher on perceived speed vs. spinners on average, but no statistically significant difference. ECCE '18.
-
Sørum & Andersen (2020) — "Does the Use of Skeleton Screens Improve Perceived Performance?" — skeletons did not consistently outperform spinners; mixed results.
-
Ziat et al. (2022) — "Malleability of time through progress bars and throbbers" — more incremental steps in progress bars shorten perceived duration. Scientific Reports.
-
Dufresne, Gutwin & Graham (2025) — "Fake it 'til you load it" — a realistic cached "false front" of the page that queues early clicks beat both a spinner and skeleton placeholders: at delays of 1000 ms and up, tasks finished ~25–28% faster and the page was rated faster and more responsive (N=72, N=96, delays 500–2000 ms). PACM HCI (EICS).
-
Inal (2016) — "User-Friendly Locations of Error Messages in Web Forms: An Eye Tracking Study" — messages next to the field were spotted fastest. Journal of Eye Movement Research.
-
"Shared attention for action selection and action monitoring in goal-directed reaching" (2018) — faster responses when feedback appears at the action location. Psychological Research.
Guides and docs
- Why GitHub's loading bar looks good — the psychology of non-linear easing in progress bars.
- Sherwin (2014) — Progress Indicators Make a Slow System Less Insufferable
- Apple HIG — Progress indicators
- Nielsen (1993) — Response Times: The 3 Important Limits — the widely cited practitioner summary of the time thresholds.
- React Suspense — official docs on streaming and fallbacks.
- Next.js Loading UI
— the
loading.tsxconvention.