🔄 Ajax: Fix a Response Interceptor Firing Before the Request Ends
Registering a response interceptor doesn’t scope itself to one request — it attaches a handler to the shared HTTP client instance that runs for every response that instance ever receives, for as long as the handler stays registered. Calling the registration method again inside a component that re-renders, without ever ejecting the previous handler, means each render adds one more handler to the stack, and all of them fire for every request on that instance — which looks exactly like “the interceptor fired too early” when it actually fired correctly, just for a different request than the one being watched.
🔎 The Problem
function OrdersList() {
// runs again on every render - never ejected
axios.interceptors.response.use(res => {
setLoading(false);
return res;
});
// after 6 renders: 6 duplicate handlers, all firing for every response
// on this axios instance, not just the one this component triggered
}
✅ Fix: Register Once, Eject on Cleanup, Scope by Request
- Register a response interceptor exactly once, outside any function that re-runs — module scope, or inside a
useEffectwith an empty dependency array that also calls the matching eject on its own interceptor id during cleanup. - If a handler genuinely needs to react to one specific request rather than every response on the instance, scope the logic at the call site by checking the response’s own URL or a custom marker, instead of relying on registration order to isolate it.
- Log the id returned by the registration call and the current count of registered interceptors during development — a growing count across renders is the clearest sign this is the actual problem before chasing timing theories.
🚨 Why This Is Dangerous
- A loading-state toggle or auth-refresh handler that silently duplicates itself across renders doesn’t crash — it just runs its side effect multiple times per request, which can mean a token refresh firing repeatedly or a spinner flickering in ways that look like a race condition instead of accumulated registrations.
An interceptor you forgot to eject doesn’t go away when the component re-renders — it just gets a sibling.




