#4339·swr

onSuccess can fire for an obsolete request after the key changes to null

Author: rikkayoruCreated Sep 25, 2026Updated Sep 25, 2026

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:

  1. Render with conversationId = "A" and a valid SWR key.
  2. The request for conversation A starts.
  3. Before the request completes, the component changes to conversationId = "B".
  4. Because another condition is temporarily not satisfied, the SWR key becomes null.
  5. The request for A completes.
  6. onSuccess is still called, but the callback comes from the latest render and therefore sees conversationId = "B".

This results in:

data: A
conversationId: B

and 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.

typescript
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

  1. Start the example.
  2. The request for conversationId = "A" starts.
  3. Click "Switch to B (key -> null)".
  4. conversationId is now "B" and the SWR key is null.
  5. Click "Resolve A request".
  6. onSuccess is invoked.

Observed output:

onSuccess: {
  data: "data-for-A",
  conversationId: "B"
}

Additional Context

SWR version:

2.5.1

React version:

18.3.0

The 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:

typescript
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:

typescript
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:

typescript
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

StackBlitz reproduction