Skip to content
Andrea Lab

ANDREA LAB / BLOG

Debounce and stale responses in React

How to coordinate remote calculations with user changes so a slow response retains its context and the visible total matches the current selection.

Someone selects two workshop seats and the server starts calculating the price. Before the response arrives, they change the quantity to four. The second calculation finishes first and displays the correct total. Then the two-seat calculation arrives and overwrites the screen.

In React with TypeScript, a timer can reduce the requests sent while the selection changes. The application also needs to decide which responses remain valid when they arrive. A remote price calculation must associate its result with the values that produced it.

Give the current intent an identity

A calculation may depend on seats, category, coupon, and workshop. If any of those values changes, the confirmed total for the previous selection no longer represents the current one. The interface can temporarily retain it with an indication that an update is pending and avoid presenting it as a confirmed price.

With a request counter, each request captures an identifier and checks whether it is still current before updating state. Apply the same rule to errors. A delayed availability error can also replace a more recent calculation if the code checks successful results alone.

Wait for a pause before sending

Debounce waits for values to remain stable for an interval before starting a calculation. For the workshop, it can group several quick quantity changes. Tune the interval to the interaction and test it under the latencies users experience.

React runs effect cleanup before setting the effect up again when its dependencies change. That provides a place to remove a pending timer and invalidate the previous operation. Its documentation demonstrates cleanup when fetching data. React useEffect.

This synthetic effect illustrates a quantity-based query for a fixed workshop. It omits other fields to focus on request coordination. The example server returns an object containing a numeric total.

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

  const timer = window.setTimeout(async () => {
    try {
      const response = await fetch(
        '/api/workshop/quote?quantity=' + quantity,
        { signal: controller.signal },
      );
      if (!response.ok) throw new Error('quote_failed');
      const data: unknown = await response.json();
      if (
        typeof data !== 'object' || data === null ||
        !('total' in data) || typeof data.total !== 'number'
      ) throw new Error('invalid_quote');

      if (active) {
        setTotal(data.total);
        setStatus('ready');
      }
    } catch {
      if (active) setStatus('error');
    }
  }, 350);

  return () => {
    active = false;
    window.clearTimeout(timer);
    controller.abort();
  };
}, [quantity]);

Each execution has its own validity flag. Cleanup deactivates it when the quantity changes or the component unmounts. A pending response then belongs to an execution that has lost permission to update the screen. In a real component, include every dependency that determines the quote and use a response contract appropriate for amounts and currency.

Cancel work that has lost its purpose

Passing an AbortSignal to fetch lets the client request cancellation of a pending operation. The example’s cleanup also cancels the timer when the request has yet to start. AbortController.

The backend may have started processing when the client cancels. Give the calculation defined effects and execution limits. The frontend validity flag determines which result can appear on screen, while the server manages work it has already received.

Coordinate immediate calculations

An Apply coupon button may require an immediate calculation. If a timer is also pending for the same values, the flow can send two requests. Define one place that controls the immediate request, removes the pending one where appropriate, and associates the result with the same selection.

Before confirming the booking, the server validates price and availability again. The displayed quote belongs to a particular moment. If seats are held temporarily, the contract should express expiry so the screen can explain when availability changes.

Test the reverse order

A relevant test holds the two-seat response, completes the four-seat response, and then releases the first. The total should still correspond to four. Repeat with an old error and change the quantity while the timer is waiting.

These sequences check both request reduction and the relationship between selection and result. For the workshop, the screen should show when a calculation is pending and which quantity supports the confirmed price.