Loading…
A short voice session: one question, one follow-up, then instant feedback — up to 5 minutes.
A race condition occurs when an older request finishes after a newer request and overwrites the newer result. Common solutions are cancelling obsolete requests with `AbortController`, tracking request identity, or using a data-fetching library that manages request lifecycles.
A frontend race condition can happen when multiple requests are started for changing input, such as a search field. Suppose the user searches for react, then quickly searches for react hooks. If the second request finishes first and the first request finishes later, the stale first response can overwrite the correct state.
One solution is to cancel the previous request:
let controller;
async function search(query) {
controller?.abort();
controller = new AbortController();
const response = await fetch(`/api/search?q=${query}`, {
signal: controller.signal
});
return response.json();
}In React, the same idea can be implemented inside an effect using an AbortController and cleanup. Another approach is to assign each request an identifier and only accept the response if it belongs to the latest request.
Cancellation is useful because it avoids unnecessary network and processing work, but cancellation alone is not a universal solution. Some operations cannot be cancelled after a certain point, and a backend mutation may already have happened. For mutations, idempotency and server-side correctness are often more important.
At the application level, libraries such as TanStack Query can also coordinate caching, deduplication, cancellation, stale data, and request lifecycles. The important principle is that an obsolete asynchronous result must not be allowed to overwrite newer state.