kipluo
React7 min read4 steps

How to Show a Loading Indicator While Fetching Data in React

The common mistake is showing a spinner the instant a request starts. Fast responses then flash a spinner for one frame. This guide builds a small hook that waits before showing the indicator, keeps it up long enough to read, cancels outdated requests, and handles errors.

You needReact 18+fetch and AbortControlleruseEffect cleanup
Loading demo
The loader runs indeterminate until a value is given, then shows complete or error states.Component page

1. Model the request as explicit states

A request is idle, loading, successful or failed. Keeping these in a single status value (rather than separate isLoading and isError booleans) makes impossible combinations, like loading and error at once, impossible to represent.

2. Avoid the one-frame spinner flash

Responses under about 300 ms feel instant without any indicator. If you show the spinner immediately, those fast requests produce a flash that looks like a glitch. Wait about 300 ms before showing it.

Once the spinner is visible, keep it on screen for at least about 500 ms. A spinner that appears and vanishes 50 ms later is just as distracting as the flash.

useDelayedFlag.ts
import { useEffect, useRef, useState } from "react";

/** Becomes true only after `active` has been true for `delay` ms,
 *  then stays true for at least `minVisible` ms. */
export function useDelayedFlag(active: boolean, delay = 300, minVisible = 500) {
  const [visible, setVisible] = useState(false);
  const shownAt = useRef(0);

  useEffect(() => {
    if (active && !visible) {
      const t = setTimeout(() => {
        shownAt.current = Date.now();
        setVisible(true);
      }, delay);
      return () => clearTimeout(t);
    }
    if (!active && visible) {
      const remaining = Math.max(0, minVisible - (Date.now() - shownAt.current));
      const t = setTimeout(() => setVisible(false), remaining);
      return () => clearTimeout(t);
    }
  }, [active, visible, delay, minVisible]);

  return visible;
}

3. Fetch with cancellation

If the user switches tabs or filters quickly, an older request can finish after a newer one and overwrite it. Aborting the previous request in the effect cleanup prevents that, and also avoids setting state after unmount.

aria-busy on the region tells assistive technology the content is updating, and a polite live region announces failures.

Invoices.tsx
import { useEffect, useState } from "react";
import { useDelayedFlag } from "./useDelayedFlag";

type Invoice = { id: string; total: number };
type State =
  | { status: "loading" }
  | { status: "success"; data: Invoice[] }
  | { status: "error"; message: string };

export function Invoices({ customerId }: { customerId: string }) {
  const [state, setState] = useState<State>({ status: "loading" });
  const showSpinner = useDelayedFlag(state.status === "loading");

  useEffect(() => {
    const controller = new AbortController();
    setState({ status: "loading" });
    fetch(`/api/invoices?customer=${customerId}`, { signal: controller.signal })
      .then((res) => {
        if (!res.ok) throw new Error(`Request failed (${res.status})`);
        return res.json() as Promise<Invoice[]>;
      })
      .then((data) => setState({ status: "success", data }))
      .catch((err: unknown) => {
        if (controller.signal.aborted) return;
        setState({ status: "error", message: err instanceof Error ? err.message : "Something went wrong" });
      });
    return () => controller.abort();
  }, [customerId]);

  return (
    <section aria-busy={state.status === "loading"} aria-label="Invoices">
      {showSpinner && (
        <div role="status" className="flex items-center gap-2 text-sm">
          <span className="spinner" aria-hidden />
          Loading invoices…
        </div>
      )}
      {state.status === "error" && <p role="alert">{state.message}</p>}
      {state.status === "success" && (
        <ul>
          {state.data.map((inv) => (
            <li key={inv.id}>{inv.id}: {inv.total}</li>
          ))}
        </ul>
      )}
    </section>
  );
}

4. Swap in an animated loader with real states

The plain spinner only says "busy". Kipluo's free Worm Loader takes the same status you already track ("running", "complete" or "error") and an optional 0–100 value for determinate progress. It renders as role="progressbar", stops looping under reduced motion, and plays a short sound on completion or failure.

InvoicesLoader.tsx
// npx kipluo add worm-loader
import { WormLoader } from "@/components/kipluo/worm-loader";

export function InvoicesLoader({ failed }: { failed: boolean }) {
  return <WormLoader status={failed ? "error" : "running"} label="Loading invoices" />;
}

Accessibility checklist

Tick each one off as you check your build. Your ticks stay in this browser.

0 of 4 checked

Build it yourself or install it

Build it yourself when

A CSS spinner plus the delayed-flag hook covers most data screens.

Install Kipluo when

You want a branded loader with determinate progress, complete and error states, reduced-motion handling and sound, in React and Flutter.

Keep building