Skip to main content
Saved

Pattern Resilience Advanced

Loading State

A loading indicator during an async operation shows users that the app is working, so they don’t give up or try again too soon.

Examples
React, Vue, Svelte and native web
Read
4 min

The problem

A user might click “Save” and see nothing happen. The button and the form look exactly the same as before, so they can’t tell whether their click registered, and they click again and accidentally submit the form twice.

The pattern

While something is loading, the app should show an indicator, so users always know what’s happening. A lot of apps leave this out.

Problem

I’ve watched users rage-click buttons because there was nothing to show the app was busy. Others refresh or navigate away in the middle of a save, because they think the app has locked up when it’s still working in the background, and they lose their work.

When content pops in without any transition, the layout shifts and users lose their place on the page.

Solution

You can disable a button that starts an async operation and show “Saving…” on it, so users know their click registered. For content that’s still being fetched, you can show placeholders that keep the layout in place, so the page doesn’t jump when the data arrives.

Skeleton screens work particularly well for content. They show the layout of the content before it arrives, and that feels faster to users than a spinner, even when the load takes the same amount of time.

For long operations, showing real progress is more useful than a spinner that just keeps going. “Uploading: 47%” gives users an idea of how much longer the upload will take, but with a spinner, they can’t tell whether it’s stuck. If you track the loading state separately from the data and error states, you can show something different for “loading,” “loaded but empty,” and “failed.”

Some actions don’t need an indicator at all. For a fast action that’s easy to undo, such as ticking a checkbox, an Optimistic Update can show the result right away and roll it back if the request fails.

Example

The first example shows a spinner while a user profile loads, and an error message if the request fails. The React and Vue versions also set a cancelled flag when userId changes, so a slow response for the previous user can’t replace the current user’s profile. Svelte’s {#await} block provides the same loading, loaded, and failed branches without any state variables, and the Web Components version only gets the user-id attribute once, so it doesn’t need the flag.

Basic Loading State

function UserProfile({ userId }) {
  const [loading, setLoading] = useState(true);
  const [user, setUser] = useState(null);
  const [error, setError] = useState(null);

  useEffect(() => {
    let cancelled = false;

    async function loadUser() {
      setLoading(true);
      setError(null);
      try {
        const data = await fetchUser(userId);
        if (!cancelled) setUser(data);
      } catch (err) {
        if (!cancelled) setError(err);
      } finally {
        if (!cancelled) setLoading(false);
      }
    }

    loadUser();
    return () => { cancelled = true; };
  }, [userId]);

  if (loading) return <div className="spinner" role="status">Loading...</div>;
  if (error) return <div className="error">Failed to load user</div>;
  return <div>{user.name}</div>;
}

Button Loading State

If you disable the button and show “Saving…” on it while the save runs, users can’t double-click it, and they know their click was received.

function SaveButton({ onSave }) {
  const [saving, setSaving] = useState(false);

  const handleClick = async () => {
    setSaving(true);
    try {
      await onSave();
    } finally {
      setSaving(false);
    }
  };

  return (
    <button
      onClick={handleClick}
      disabled={saving}
      aria-busy={saving}
    >
      {saving ? 'Saving...' : 'Save'}
    </button>
  );
}

Skeleton Screen

Skeleton placeholders keep the layout in place while the list of users loads, and they give users a rough idea of what the content will look like. The container has aria-busy while the skeletons are showing, and an empty list gets its own message, so users don’t mistake “loaded but empty” for a list that’s still loading.

function UserList({ users, loading }) {
  if (loading) {
    return (
      <div className="user-list" aria-busy="true">
        {[1, 2, 3].map(i => (
          <div key={i} className="user-skeleton">
            <div className="skeleton-avatar" />
            <div className="skeleton-text" />
          </div>
        ))}
      </div>
    );
  }
  if (users.length === 0) {
    return <p className="user-list-empty">No users yet.</p>;
  }
  return (
    <div className="user-list">
      {users.map(user => <UserCard key={user.id} user={user} />)}
    </div>
  );
}
.skeleton-avatar {
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
  background-size: 200% 100%;
  animation: shimmer 1.5s infinite;
}

@keyframes shimmer {
  from { background-position: 200% 0; }
  to { background-position: -200% 0; }
}

Progress Bar

For long-running operations like file uploads, a progress bar shows how much of the file has uploaded, so users can tell roughly how much longer it’ll take.

function FileUpload() {
  const [uploading, setUploading] = useState(false);
  const [progress, setProgress] = useState(0);

  const handleUpload = async (file) => {
    setUploading(true);
    setProgress(0);

    try {
      await uploadFile(file, (progressEvent) => {
        const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total);
        setProgress(percent);
      });
    } finally {
      setUploading(false);
    }
  };

  return (
    <div>
      <input type="file" onChange={(e) => handleUpload(e.target.files[0])} />
      
      {uploading && (
        <div
          className="progress-bar"
          role="progressbar"
          aria-label="Upload progress"
          aria-valuemin={0}
          aria-valuemax={100}
          aria-valuenow={progress}
        >
          <div className="progress-fill" style={{ width: `${progress}%` }} />
          <span>{progress}%</span>
        </div>
      )}
    </div>
  );
}

Delayed Loading Indicator

For fast operations, a short delay before showing the spinner stops it from flickering on and off when the content loads quickly.

function DataDisplay() {
  const [showSpinner, setShowSpinner] = useState(false);
  const [data, setData] = useState(null);

  useEffect(() => {
    // Only show spinner if loading takes longer than 200ms
    const timer = setTimeout(() => setShowSpinner(true), 200);

    fetchData()
      .then(result => setData(result))
      .finally(() => {
        clearTimeout(timer);
        setShowSpinner(false);
      });

    return () => clearTimeout(timer);
  }, []);

  if (showSpinner) return <Spinner />;
  return data ? <Content data={data} /> : null;
}

Inline Loading State

A small spinner inside the search box shows that results are loading, right where the user is typing. The role="status" element stays on the page the whole time, so screen readers announce the hidden “Searching…” text when it appears inside that element.

function SearchBox() {
  const [query, setQuery] = useState('');
  const [searching, setSearching] = useState(false);
  const [results, setResults] = useState([]);
  const controllerRef = useRef(null);

  const handleSearch = async (q) => {
    // Cancel the previous request so an older response can't overwrite newer results
    controllerRef.current?.abort();
    const controller = new AbortController();
    controllerRef.current = controller;

    setSearching(true);
    try {
      const data = await search(q, { signal: controller.signal });
      if (!controller.signal.aborted) setResults(data);
    } catch (err) {
      if (err.name !== 'AbortError') throw err;
    } finally {
      if (controllerRef.current === controller) setSearching(false);
    }
  };

  return (
    <div>
      <div className="search-input-wrapper">
        <input
          type="search"
          value={query}
          onChange={(e) => { setQuery(e.target.value); handleSearch(e.target.value); }}
        />
        <span role="status">
          {searching && (
            <span className="spinner-inline">
              <span className="visually-hidden">Searching...</span>
            </span>
          )}
        </span>
      </div>
      <ul>
        {results.map(r => <li key={r.id}>{r.title}</li>)}
      </ul>
    </div>
  );
}

Benefits

  • Users are less likely to rage-click, because they can see that their click registered and that the app is working on it.
  • Fewer users leave the page, because they’re less likely to refresh or navigate away when they can see something is happening.
  • Skeleton screens make the page feel faster to users than a spinner does, even when the load takes the same amount of time.
  • Users can tell the difference between “loading,” “loaded but empty,” and “failed.”
  • A disabled button prevents accidental double-clicks, so users don’t submit the same form twice.
  • A progress bar like “Uploading: 47%” shows users that the upload is moving and gives them an idea of how long is left.
  • Skeletons reserve space for the content, so the page doesn’t jump when it arrives.

Tradeoffs

  • If each operation shows its own indicator, your UI can end up with spinners all over the page.
  • A spinner that flashes up for 50ms on a fast operation is more annoying than no spinner at all, so you should add a short delay before showing any loading UI.
  • Each component needs more state, with loading, data, and error instead of just the data.
  • Skeleton screens need maintenance, because when the content layout changes, you have to update the skeletons to match.
  • Progress indicators need support from the backend, and if your API doesn’t report progress events, you can’t show meaningful percentages.
  • A polished loading state can make it easy to ignore a slow operation, but a better spinner doesn’t make the operation any faster.
  • It’s easy to leave out ARIA attributes like role="status" and aria-busy without noticing, and then screen reader users aren’t told that anything is loading.

Summary

A loading state tells users that your app is working, so they’re less likely to get confused or repeat an action while an asynchronous operation runs. A “Saving…” label works well on a button, and skeleton screens work well for content. A quick operation might only need an indicator after a short delay, so it doesn’t flicker, and a long one should show progress, so users know how long is left.

See also

Next in Resilience Response Regeneration Users can re-run a prompt for a different response, and the app keeps each earlier attempt as a variant they can switch back to.

A monthly email
from Den Odell.

What I'm thinking about frontend patterns, plus news when the site changes.

No spam. Unsubscribe anytime.