The race condition behind stale UI

A React widget that fetches from several API endpoints and re-fetches as the user interacts can end up showing the wrong thing. When clicks come faster than responses, each earlier request still resolves and writes its payload into the UI, so outdated data appears briefly before the final request corrects it. On slow connections the flash is more pronounced, and every superseded request still consumes the user's bandwidth.

Debouncing interactions does not fix this: debounced or not, the stale fetches resolve and update state until the last one lands. The demo for this problem pulls game deals from the Cheap Shark API with fetch(); rapidly changing the price limit makes the UI flicker through wrong values.

Aborting with AbortController

Pending DOM asynchronous requests can be cancelled with an AbortController, which also works for event listeners. The interface exposes an AbortSignal that is passed into the fetch() call:

const abortController = new AbortController()
const signal = abortController.signal
fetch(url, { signal })

Once wired up, calling abortController.abort() cancels the pending fetch.

Wiring it into the component

The revised example keeps only the newest response, via four changes:

  1. A cached abortController variable lives in a useRef in the <App /> component.
  2. Each new fetch creates a fresh AbortController and reads its AbortSignal.
  3. That signal is handed to the fetch() call.
  4. The controller aborts itself when the next fetch begins.
const App = () => {
 // Same as before, local variable and state declaration
 // ...

 // Create a new cached variable abortController in a useRef() hook
 const abortController = React.useRef()

 React.useEffect(() => {
  // If there is a pending fetch request with associated AbortController, abort
  if (abortController.current) {
    abortController.abort()
  }
  // Assign a new AbortController for the latest fetch to our useRef variable
  abortController.current = new AbortController()
  const { signal } = abortController.current

  // Same as before
  fetch(url, { signal }).then(res => {
    // Rest of our fetching logic, same as before
  })
 }, [
  abortController,
  sortByString,
  upperPrice,
  lowerPrice,
 ])
}

Combined with debouncing the UI interactions, this covers both sides: redundant requests are never left running, and the UI renders once with the latest API data rather than transitioning through outdated responses.