DEV Community

Zeeland
Zeeland

Posted on

React Loading States: Spinner, Skeleton, or Progress?

Choose a loading state from the information your application actually has. A spinner says that work is happening. A skeleton shows the shape of content that has yet to arrive. A progress indicator reports measured completion. None of these can tell a user what happens after a request fails unless you build that state too.

The practical question is: what does the person waiting need to know, and what can the application truthfully tell them?

Situation Start with What to communicate
A local action is pending and you do not know its completion percentage A small spinner or dots beside the action What is happening, with the action guarded against duplicate submission
A known card, list, or profile layout is waiting for its first content A skeleton shaped like that content Where the content will appear, without inventing text or fake completion estimates
An upload or other task reports a meaningful completed amount and total A progress indicator The measured fraction and which stage it describes
Existing content is being refreshed Keep useful content visible and add a pending message Which content is refreshing, without presenting stale content as a fresh response

These are implementation choices based on what your state machine knows. Test each choice against the actual task and every state your application can enter.

Start with the state model

A boolean named loading is rarely enough. A results panel can be idle, loading, ready, empty, or in error. An upload can be sending bytes, processing on the server, complete, cancelled, or failed. Decide how each state appears before choosing the animation.

Keep the loading message close to the affected content. When one card updates, replacing the whole page with a spinner hides useful context. When a request fails, replace the pending state with a clear explanation and a real recovery action. Retry should start a new request instead of merely restarting an animation.

Use a spinner or dots for unknown progress

Mova UI Loaders includes small animated indicators such as Pulse Dots, whose public source renders three staggered dots. The visual component does not know whether your request is pending, and it does not supply an accessible loading announcement on its own. Your application code needs to provide both.

In an existing React project, you can copy the component source directly into your repo with the Mova CLI:

npx @mova-ui/react@0.8.0 add pulse-dots
Enter fullscreen mode Exit fullscreen mode

The CLI writes src/components/mova/pulse-dots.tsx and styles.css (requiring React 18.2+ or 19 and React DOM). Import the generated CSS once at your app entry. Check the CLI documentation or the Mova UI GitHub repository for the latest package version and component catalog.

The example below makes a real HTTP request when the user activates the button. Its endpoint returns { items: string[] }, so you can test delayed responses, HTTP errors, invalid JSON shapes, and empty arrays over real HTTP instead of toggling a fake local boolean.

import React, { useEffect, useId, useRef, useState } from 'react';
import { PulseDots } from './components/mova/pulse-dots';
import './components/mova/styles.css';
import './loading.css';

type ResultState =
  | { phase: 'idle' | 'loading' }
  | { phase: 'ready'; items: string[] }
  | { phase: 'error'; message: string };

// The endpoint must return JSON: { items: string[] }.
export function Results({ endpoint = '/api/results' }: { endpoint?: string }) {
  const [state, setState] = useState<ResultState>({ phase: 'idle' });
  const request = useRef<AbortController | null>(null);
  const generation = useRef(0);
  const regionId = useId();

  useEffect(() => {
    setState({ phase: 'idle' });
    return () => {
      generation.current += 1;
      request.current?.abort();
      request.current = null;
    };
  }, [endpoint]);

  async function load() {
    if (request.current) return;
    const controller = new AbortController();
    request.current = controller;
    const current = ++generation.current;
    setState({ phase: 'loading' });
    try {
      const response = await fetch(endpoint, {
        signal: controller.signal,
        headers: { Accept: 'application/json' },
      });
      if (!response.ok) throw new Error(`HTTP ${response.status}`);
      const data: unknown = await response.json();
      if (
        !data ||
        typeof data !== 'object' ||
        !('items' in data) ||
        !Array.isArray(data.items) ||
        !data.items.every((item) => typeof item === 'string')
      ) {
        throw new Error('Invalid results response');
      }
      if (current === generation.current) {
        setState({ phase: 'ready', items: data.items });
      }
    } catch (error) {
      if (!controller.signal.aborted && current === generation.current) {
        const detail = error instanceof Error ? error.message : 'Request failed';
        setState({ phase: 'error', message: `Results could not load (${detail}).` });
      }
    } finally {
      if (current === generation.current) request.current = null;
    }
  }

  const pending = state.phase === 'loading';
  const status = pending
    ? 'Loading results...'
    : state.phase === 'ready'
      ? state.items.length
        ? `${state.items.length} results ready.`
        : 'No results found.'
      : '';

  return (
    <>
      <button onClick={load} aria-disabled={pending} aria-controls={regionId}>
        {pending
          ? 'Loading...'
          : state.phase === 'error'
            ? 'Try again'
            : state.phase === 'ready'
              ? 'Reload results'
              : 'Load results'}
      </button>
      <p role="status" aria-atomic="true">
        {status}
      </p>
      {state.phase === 'error' && <p role="alert">{state.message}</p>}
      <section id={regionId} aria-label="Search results" aria-busy={pending}>
        {pending && (
          <div className="loading-motion" aria-hidden="true">
            <PulseDots />
          </div>
        )}
        {state.phase === 'ready' && state.items.length > 0 && (
          <ul>
            {state.items.map((item, index) => (
              <li key={index}>{item}</li>
            ))}
          </ul>
        )}
      </section>
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode
@media (prefers-reduced-motion: reduce) {
  .loading-motion {
    display: none;
  }
}
Enter fullscreen mode Exit fullscreen mode

A few implementation details matter here:

  • Keep the request button mounted so a keyboard user keeps focus across retries. aria-disabled communicates the pending state while the ref guard prevents duplicate requests.
  • Check response.ok explicitly. A resolved fetch promise does not mean HTTP 200. Validate the JSON shape before rendering. See MDN: Using the Fetch API.
  • Keep the decorative dots hidden from assistive technology (aria-hidden="true") while keeping the role="status" region mounted outside the aria-busy results container. Always verify announcements with your target browser and screen reader before shipping. See WAI-ARIA status and busy definitions.
  • Respect OS motion settings with prefers-reduced-motion. Hiding decorative motion leaves the status text intact rather than assuming a shorter animation duration works for every user. See MDN: prefers-reduced-motion.

Use a skeleton when you know the layout

A skeleton works best when it closely matches the content that will replace it. A profile placeholder can reserve an avatar and two text lines. A table placeholder should match the real column layout. Avoid showing arbitrary rows that promise a structure the API response will never return.

If you want a starting point for a compact avatar-and-lines placeholder, Mova ships skeleton-loader (a compact 120px-max visual you should resize to your real container after inspecting its source):

npx @mova-ui/react@0.8.0 add skeleton-loader
Enter fullscreen mode Exit fullscreen mode

You can also inspect other loading patterns such as Border Trail Loading in the Mova UI catalog.

Treat skeleton shapes as decorative and provide one clear loading message for the region. Reserve space deliberately in the surrounding layout, and verify transitions across real text lengths, images, and responsive breakpoints instead of assuming a skeleton automatically eliminates layout shift.

For React code that suspends, a <Suspense> boundary can show the matching fallback. A fetch call inside useEffect does not trigger a Suspense boundary by itself, so follow your framework's data-loading layer or manage explicit request state as shown above. See React: Suspense.

Use progress when completion is measurable

When an upload or multi-step job reports real bytes sent and total bytes, a native <progress> element communicates that measurement directly:

<>
  <label htmlFor="upload-progress">Uploading file</label>
  <progress id="upload-progress" value={40} max={100} />
  <p>40% of bytes uploaded</p>
</>
Enter fullscreen mode Exit fullscreen mode

Derive value from real completed progress rather than a fake timer. If the total size is unknown, omit the value attribute to render an indeterminate native indicator. Always label the control explicitly, because text placed inside <progress> is not its accessible label. See MDN: progress.

Finishing the transfer does not always mean server processing is done. Switch the label or state once bytes finish uploading and server-side processing starts. Reserve <progress> for task completion; use <meter> for a scalar measurement within a known range. See W3C APG: Meter Pattern.

Verify transitions before picking the animation

Before polishing timing curves, walk through five real cases: a slow success, an empty result, an HTTP failure, a keyboard retry, and a refresh while stale data is already on screen.

Check three things every time:

  1. Changing request parameters aborts the in-flight browser fetch and invalidates its generation counter so an older response cannot overwrite newer state. Note that aborting in the browser does not guarantee the server cancels work already accepted; see React: useEffect.
  2. Keyboard focus stays predictable on retry and never gets trapped or dropped when a button disables or unmounts.
  3. Pending indicators disappear cleanly when work settles, leaving the next useful user action visible.

If you want copy-paste React motion primitives and loading components with live playgrounds and zero lock-in, explore Mova UI or install individual components with npx @mova-ui/react add <component>.

Top comments (0)