Back to Writing

Beyond the Happy Path — 01

The User Clicked 36. We Showed 35.

Two product requests succeed. The one that finishes last puts the wrong product on screen.

Zain Ali7 min readFrontend Engineering / Async UI
Beyond the Happy Path poster showing Product 36 loading first and a late Product 35 response overwriting it

The detail panel switched back

You’re comparing products in a catalog. You click Product 35, then spot Product 36 and click it before the detail panel finishes loading. Product 36 appears with the right name and price. A moment later, the panel switches to Product 35. The selection still points to 36, and you haven’t clicked anything else.

In the Network tab, both requests are green. Each endpoint returned the product it was asked for. The mistake happened in the browser, where the response for 35 was still allowed to update a panel that now belonged to 36.

How the requests raced

The clicks determine when the requests start. The network and server determine when they finish. When two requests can write to the same panel, the order in which they finish can determine what the user sees. That’s the race condition.

Request timeline in the unguarded panel
TimeEventSelectedPanel
T1User selects Product 35. Request A starts.35Loading
T2User selects Product 36. Request B starts.36Loading
T3Request B returns Product 36.36Product 36
T4Request A returns Product 35.36Product 35 (stale)

The decisive moment is T4. Product 35 is valid data for Request A. The selection, which represents the user’s latest intent, is still 36. The displayed state diverges from that intent when A’s result is applied to the panel.

This is easy to miss when you develop against a fast local API or verify each product in isolation. A cache hit for 36 and a slower lookup for 35 can reverse the completion order, even when both requests eventually succeed.

Same request sequence, two results

The demo selects Product 35, then switches to Product 36.

Unconditional update

Ready

Guarded update

Ready

Where the unguarded update happens

Suppose the product list passes its current selection to a detail component. Each change to productId starts a new fetch. For the examples, assume the endpoint returns a JSON object with a name on success.

Before · ProductDetails.jsx
"use client";

import { useEffect, useState } from "react";

export function ProductDetails({ productId }) {
  const [product, setProduct] = useState(null);
  const [error, setError] = useState("");

  useEffect(() => {
    async function load() {
      try {
        const response = await fetch(`/api/products/${productId}`);
        if (!response.ok) throw new Error(`HTTP ${response.status}`);
        setProduct(await response.json());
      } catch {
        setError("Could not load product details.");
      }
    }

    void load();
  }, [productId]);

  if (error) return <p role="alert">{error}</p>;
  return <p>{product?.name ?? "Loading product…"}</p>;
}

Each effect closes over its own productId, so each URL is correct. The call to setProduct writes to the same state in both cases. Starting the second effect leaves the first request’s continuation free to run. An obsolete request can overwrite the product or publish an error for a selection the user has already left.

Give each selection its own request identity

Assign a fresh identity whenever the user selects or retries a product. Capture that identity when the request begins, then compare it with the current identity when applying the result. The product ID alone is insufficient. In a 35 → 36 → 35 sequence, the first and third requests both ask for 35, but only the third belongs to the latest selection.

Use effect cleanup to retire old work

React calls the previous effect’s cleanup when its dependencies change, and again for the current effect when the component unmounts. A flag scoped to one effect setup lets its asynchronous work see that it has been retired. Keep the identity check at the state update too. It protects the transition if a result is already queued while the user changes the selection.

Cancel obsolete fetches

Pass an AbortSignal to fetch and abort during cleanup. Fetch can stop waiting for a response or reading its body. Work that ignores the signal, such as a separate promise-based transformation, can still finish. The server may also have processed the request by then. Use cancellation to stop work where supported and the identity check to decide what reaches the panel.

After · ProductPicker.jsx
"use client";

import { useEffect, useState } from "react";

export function ProductPicker() {
  const [state, setState] = useState({
    intent: { productId: 35 },
    status: "loading",
  });
  const { intent } = state;

  function select(productId) {
    // A fresh object identifies every selection, including retries.
    setState({ intent: { productId }, status: "loading" });
  }

  useEffect(() => {
    const controller = new AbortController();
    let active = true;

    function publish(result) {
      if (!active) return;
      setState(current =>
        current.intent === intent ? { intent, ...result } : current
      );
    }

    async function load() {
      try {
        const response = await fetch(
          `/api/products/${intent.productId}`,
          { signal: controller.signal }
        );

        if (!response.ok) throw new Error(`HTTP ${response.status}`);
        const product = await response.json();
        publish({ status: "success", product });
      } catch {
        publish({ status: "error" });
      }
    }

    void load();
    return () => {
      active = false;
      controller.abort();
    };
  }, [intent]);

  return (
    <div>
      {[35, 36].map(id => (
        <button
          key={id}
          type="button"
          aria-pressed={intent.productId === id}
          onClick={() => select(id)}
        >
          Product {id}
        </button>
      ))}
      {state.status === "loading" && (
        <p role="status">Loading Product {intent.productId}…</p>
      )}
      {state.status === "error" && (
        <p role="alert">Could not load Product {intent.productId}.</p>
      )}
      {state.status === "success" && (
        <p role="status">{state.product.name}</p>
      )}
    </div>
  );
}

The picker stores the selection and its status together. A click establishes a fresh intent and immediately queues its loading state, which clears the previous product or error. A single publish function handles both success and failure. It skips retired effects and uses a functional state update to check whether the request still owns the panel.

The response.ok check converts non-success HTTP responses into the current selection’s error state. Cleanup marks its effect inactive before aborting, so the aborted request’s rejection stays quiet. Loading ends when the current request succeeds or fails. A shared finally that clears loading for every request would let an old completion hide the new selection’s loading indicator.

This picker clears the previous product as soon as the selection changes. A catalog could keep the previous details visible during loading to avoid a layout shift. In that design, keep the displayed product’s identity explicit and tie actions like adding to a cart to the product the panel actually represents. The loading treatment is a product decision. The ownership check applies either way.

Why debouncing is not enough

Debouncing controls how frequently requests start. It can collapse a burst of keystrokes into one search, but a request that starts after a pause can still overlap with one from the next pause. The moment the user changes the selection, any earlier response needs to satisfy the same relevance check, even if the next request is waiting for the debounce timer.

Test the completion order

Delay Product 35 in a local API stub or browser route intercept. Select 35, wait until its request has started, then select 36. Return Product 36 first and confirm that it appears. Now release Product 35. The unguarded panel reverts to 35. The corrected panel keeps 36 selected and displayed.

For an automated component test, resolve the fetch promises by hand to control their order. The mock deliberately ignores the abort signal so the obsolete work still completes. This verifies that the state guard protects the panel even when cancellation cannot stop a result.

Regression test with Vitest and React Testing Library
ProductPicker.test.jsx
// @vitest-environment jsdom
import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, expect, it, vi } from "vitest";
import { ProductPicker } from "./ProductPicker";

afterEach(() => {
  cleanup();
  vi.unstubAllGlobals();
});

it("keeps Product 36 after Product 35 arrives late", async () => {
  const pending = new Map();
  const fetchStub = vi.fn(url => new Promise(resolve => {
    pending.set(url, resolve);
  }));
  vi.stubGlobal("fetch", fetchStub);

  render(<ProductPicker />);
  fireEvent.click(screen.getByRole("button", { name: "Product 36" }));
  await waitFor(() => expect(pending.size).toBe(2));

  async function resolveProduct(id) {
    await act(async () => {
      pending.get(`/api/products/${id}`)(
        Response.json({ name: `Details for Product ${id}` })
      );
    });
  }

  await resolveProduct(36);
  expect(screen.getByRole("status").textContent).toBe("Details for Product 36");

  await resolveProduct(35);
  expect(screen.getByRole("status").textContent).toBe("Details for Product 36");
  expect(screen.getByRole("button", { name: "Product 36" })
    .getAttribute("aria-pressed")).toBe("true");
});

Repeat with a rejected request for 35 while 36 is still loading. Product 36’s loading indicator should stay visible, and the stale error should never reach the panel.

The same bug in other interfaces

Autocomplete can show suggestions for the previous query. A profile switcher can load an earlier user’s details. A dashboard or filtered data view can show totals for the old filter next to the new filter controls. In each case, identify the user choice that owns the view. If a query cache holds several results, key it by the inputs that define each result and render from the active key. An older result can be worth caching for later without being eligible to replace the active view.

The related essay Your React UI May Be Buggy Because It Remembers Too Much covers another way the displayed result can drift from the state that should control it.

Takeaway

Before applying a result, check that it still belongs to the user’s current selection.

A successful API response isn't always a valid UI update.

ZA
AUTHOR & ENGINEER

Zain Ali

Full-Stack Developer · Pakistan

HeyZain is the engineering portfolio and technical publication of Zain Ali, a full-stack developer and software engineer specializing in Next.js, React, Node.js, TypeScript, and MongoDB. He builds production-ready web platforms, SaaS products, marketplaces, and developer tools from schema design to edge deployment.