Skip to content

New fix for hydration loop bug #9188

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
May 25, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions packages/query-core/src/hydration.ts
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,7 @@ export function hydrate(

let query = queryCache.get(queryHash)
const existingQueryIsPending = query?.state.status === 'pending'
const existingQueryIsFetching = query?.state.fetchStatus === 'fetching'

// Do not hydrate if an existing query exists with newer data
if (query) {
Expand Down Expand Up @@ -249,6 +250,7 @@ export function hydrate(
if (
promise &&
!existingQueryIsPending &&
!existingQueryIsFetching &&
// Only hydrate if dehydration is newer than any existing data,
// this is always true for new queries
(dehydratedAt === undefined || dehydratedAt > query.state.dataUpdatedAt)
Expand Down
2 changes: 1 addition & 1 deletion packages/react-query/src/HydrationBoundary.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ export const HydrationBoundary = ({
existingQuery.state.dataUpdatedAt ||
(dehydratedQuery.promise &&
existingQuery.state.status !== 'pending' &&
existingQuery.state.fetchStatus !== 'fetching' &&
dehydratedQuery.dehydratedAt !== undefined &&
dehydratedQuery.dehydratedAt > existingQuery.state.dataUpdatedAt)

Expand Down Expand Up @@ -110,7 +111,6 @@ export const HydrationBoundary = ({
React.useEffect(() => {
if (hydrationQueue) {
hydrate(client, { queries: hydrationQueue }, optionsRef.current)
// eslint-disable-next-line @eslint-react/hooks-extra/no-direct-set-state-in-use-effect
setHydrationQueue(undefined)
}
}, [client, hydrationQueue])
Expand Down
38 changes: 23 additions & 15 deletions packages/react-query/src/__tests__/HydrationBoundary.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@ import {
QueryClient,
QueryClientProvider,
dehydrate,
hydrate,
useQuery,
} from '..'
import type { hydrate } from '@tanstack/query-core'

describe('React hydration', () => {
let stringifiedState: string
Expand Down Expand Up @@ -368,6 +368,7 @@ describe('React hydration', () => {

// https://github.com/TanStack/query/issues/8677
test('should not infinite loop when hydrating promises that resolve to errors', async () => {
const originalHydrate = coreModule.hydrate
const hydrateSpy = vi.spyOn(coreModule, 'hydrate')
let hydrationCount = 0
hydrateSpy.mockImplementation((...args: Parameters<typeof hydrate>) => {
Expand All @@ -379,9 +380,19 @@ describe('React hydration', () => {
// logic in HydrationBoundary is not working as expected.
throw new Error('Too many hydrations detected')
}
return hydrate(...args)
return originalHydrate(...args)
})

// For the bug to trigger, there needs to already be a query in the cache,
// with a dataUpdatedAt earlier than the dehydratedAt of the next query
const clientQueryClient = new QueryClient()
await clientQueryClient.prefetchQuery({
queryKey: ['promise'],
queryFn: () => 'existing',
})

await vi.advanceTimersByTimeAsync(100)

const prefetchQueryClient = new QueryClient({
defaultOptions: {
dehydrate: {
Expand All @@ -393,26 +404,21 @@ describe('React hydration', () => {
queryKey: ['promise'],
queryFn: async () => {
await sleep(10)
return Promise.reject('Query failed')
throw new Error('Query failed')
},
})

const dehydratedState = dehydrate(prefetchQueryClient)

// Avoid redacted error in test
dehydratedState.queries[0]?.promise?.catch(() => {})
await vi.advanceTimersByTimeAsync(10)
function ignore() {
// Ignore redacted unhandled rejection
}
process.addListener('unhandledRejection', ignore)

// Mimic what React/our synchronous thenable does for already rejected promises
// @ts-expect-error
dehydratedState.queries[0].promise.status = 'failure'

// For the bug to trigger, there needs to already be a query in the cache
const queryClient = new QueryClient()
await queryClient.prefetchQuery({
queryKey: ['promise'],
queryFn: () => 'existing',
})

function Page() {
const { data } = useQuery({
queryKey: ['promise'],
Expand All @@ -426,7 +432,7 @@ describe('React hydration', () => {
}

const rendered = render(
<QueryClientProvider client={queryClient}>
<QueryClientProvider client={clientQueryClient}>
<HydrationBoundary state={dehydratedState}>
<Page />
</HydrationBoundary>
Expand All @@ -436,8 +442,10 @@ describe('React hydration', () => {
expect(rendered.getByText('existing')).toBeInTheDocument()
await vi.advanceTimersByTimeAsync(10)
expect(rendered.getByText('new')).toBeInTheDocument()

process.removeListener('unhandledRejection', ignore)
hydrateSpy.mockRestore()
prefetchQueryClient.clear()
queryClient.clear()
clientQueryClient.clear()
})
})
Loading