Fix fetch race conditions inside useEffect
A slow earlier request can overwrite a newer result. Ignore the stale response with a cleanup flag, or cancel it with an AbortController.
You typed a and then ab into a search box. The screen says ab, and a moment later the results change to the ones for a.
The effect started two requests. The one for a was slower, it finished last, and its setState ran after the one for ab. I reproduced it with React under Node, using a fake fetch where a takes 300 ms and ab takes 50 ms.
useEffect(() => {
fetch(`/search?q=${encodeURIComponent(query)}`)
.then((res) => res.json())
.then((data) => setText(data))
}, [query])
// after 100 ms: query "ab": results for "ab"
// after 400 ms: query "ab": results for "a"The query on screen is ab and the results under it belong to a. Nothing in the effect says the first request is out of date once query has changed.
Ignore the old response
React runs the cleanup function returned from an effect before it runs the effect again. Use it to mark that run as stale.
useEffect(() => {
let ignore = false
fetch(`/search?q=${encodeURIComponent(query)}`)
.then((res) => {
if (!res.ok) throw new Error(`Search failed (${res.status})`)
return res.json()
})
.then((data) => {
if (!ignore) setText(data)
})
.catch((error) => {
if (!ignore) setError(error)
})
return () => {
ignore = true
}
}, [query])Each run of the effect gets its own ignore. When query changes, the old run's flag becomes true, so its late response is dropped. The request for a still runs to the end; only its answer is thrown away.
The same harness now prints results for "ab" at both 100 ms and 400 ms.
Cancel the old request
An AbortController does the same job and also cancels the request. The cleanup calls abort() and the pending fetch rejects with an AbortError.
useEffect(() => {
const controller = new AbortController()
const { signal } = controller
fetch(`/search?q=${encodeURIComponent(query)}`, { signal })
.then((res) => {
if (!res.ok) throw new Error(`Search failed (${res.status})`)
return res.json()
})
.then((data) => {
if (!signal.aborted) setText(data)
})
.catch((error) => {
if (!signal.aborted) setError(error)
})
return () => controller.abort()
}, [query])The output matches the flag version. Against a real local server, aborting made the server log that the connection closed before it sent a response.
Leave the catch out and the rejection is unhandled. In my Node harness it killed the process with the AbortError.
I use the flag when the effect does more than fetch, since it works for any async step. I use AbortController when the request is large enough that I want it to stop. Here setText and setError are state setters. Use the error state to show a failed search. JavaScript promises from extra processing may keep running after you abort, so check the signal before updating state.