onSuccess can fire for an obsolete request after the key changes to null
Bug report
Description / Observed Behavior
When a useSWR request is in flight and the SWR key changes from a valid key to null, the previous request can still invoke onSuccess.
This can cause a race condition when onSuccess closes over values from the latest render.
For example:
- Render with
conversationId = "A"and a valid SWR key. - The request for conversation A starts.
- Before the request completes, the component changes to
conversationId = "B". - Because another condition is temporarily not satisfied, the SWR key becomes
null. - The request for A completes.
onSuccessis still called, but the callback comes from the latest render and therefore seesconversationId = "B".
This results in:
data: A
conversationId: Band can lead to application state being written to the wrong conversation.
Expected Behavior
Once the SWR key changes from a valid key to null, I would expect an in-flight request associated with the previous key to be treated as obsolete.
In particular, its onSuccess callback should not be invoked after the hook has transitioned to the null key.
Repro Steps / Code Example
The following example uses a manually controlled promise so the race can be reproduced deterministically.
import { useState } from 'react'
import useSWR from 'swr'
let resolveA: (() => void) | undefined
const fetcher = async ([, conversationId]: [string, string]) => {
return new Promise<string>(resolve => {
if (conversationId === 'A') {
resolveA = () => {
resolve(`data-for-${conversationId}`)
}
} else {
resolve(`data-for-${conversationId}`)
}
})
}
export default function App() {
const [enabled, setEnabled] = useState(true)
const conversationId = enabled ? 'A' : 'B'
// When enabled becomes false, the key becomes null.
const key = enabled
? ['/api/conversation', conversationId]
: null
useSWR(key, fetcher, {
onSuccess(data) {
console.log('onSuccess:', {
data,
conversationId
})
}
})
return (
<div>
<button onClick={() => setEnabled(false)}>
Switch to B (key -> null)
</button>
<button onClick={() => resolveA?.()}>
Resolve A request
</button>
</div>
)
}Steps
- Start the example.
- The request for
conversationId = "A"starts. - Click "Switch to B (key -> null)".
conversationIdis now"B"and the SWR key isnull.- Click "Resolve A request".
onSuccessis invoked.
Observed output:
onSuccess: {
data: "data-for-A",
conversationId: "B"
}Additional Context
SWR version:
2.5.1React version:
18.3.0The behavior appears to be related to the interaction between keyRef, configRef, and callbackSafeguard in src/index/use-swr.ts.
In the current implementation, the effect that updates the key ref contains:
useIsomorphicLayoutEffect(() => {
if (!key) return
// ...
keyRef.current = key
// ...
}, [key])So when the key changes from a valid key to the falsy serialized value produced by null, the effect returns before updating keyRef.current.
Later, callbackSafeguard() checks:
const callbackSafeguard = () => {
if (IS_REACT_LEGACY) {
return (
!unmountedRef.current &&
key === keyRef.current &&
initialMountedRef.current
)
}
return key === keyRef.current
}At that point, the old request still has the old key and keyRef.current may still contain that same old key, so the safeguard passes.
The success callback is then invoked through:
getConfig().onSuccess(newData, key, config)configRef.current is updated separately on each render, which means the callback can come from the latest render even though newData belongs to the obsolete request.
Relevant source:
https://github.com/vercel/swr/blob/main/src/index/use-swr.ts
I am not sure whether the intended fix is to update keyRef.current before the if (!key) return, or to add an additional safeguard for the key -> null transition. I wanted to report the reproducible behavior first.
Reproduction
Source: vercel/swr