The correct and modern approach is to use AbortController so that only the latest request remains active.
β Best Practice (Frontend – Browser / React)
πΉ Step-by-step Approach
- Keep a reference to the previous request
- Abort it before starting a new one
- Create a new
AbortControllerfor the new request
π§ͺ Example (Plain JavaScript)
let controller;
function fetchData() {
// Cancel previous request
if (controller) {
controller.abort();
}
// Create new controller
controller = new AbortController();
fetch("/api/data", { signal: controller.signal })
.then(res => res.json())
.then(data => console.log(data))
.catch(err => {
if (err.name === "AbortError") {
console.log("Previous request cancelled");
}
});
}
π§ͺ Example (React Component – Recommended)
import { useEffect, useRef } from "react";
function Search({ query }) {
const abortRef = useRef(null);
useEffect(() => {
if (!query) return;
// Cancel previous request
abortRef.current?.abort();
const controller = new AbortController();
abortRef.current = controller;
fetch(`/api/search?q=${query}`, {
signal: controller.signal
})
.then(res => res.json())
.then(console.log)
.catch(err => {
if (err.name !== "AbortError") {
console.error(err);
}
});
return () => controller.abort(); // cleanup
}, [query]);
return null;
}
π§ Why This Works
- Only one active request at a time
- Prevents race conditions
- Prevents outdated responses from updating UI
- Improves performance & UX
β What Happens on Backend?
- Backend still receives the request
- Frontend stops listening
- Backend can optionally detect disconnect using:
req.on("close", () => console.log("Client disconnected"));
π§ͺ Axios Alternative (Bonus)
const controller = new AbortController();
axios.get("/api/data", {
signal: controller.signal
});
controller.abort();
π― Short Interview Answer
When a new API call is triggered, the previous request should be canceled using
AbortController. Before starting the new request, callabort()on the previous controller so only the latest request remains active, preventing race conditions and stale data updates.
β One-line summary
Abort the previous request using AbortController before firing a new API call.