Skip to content

Commit 9c52898

Browse files
committed
fix(query-core): do not schedule garbage collection on the server
1 parent 2969edf commit 9c52898

3 files changed

Lines changed: 29 additions & 0 deletions

File tree

.changeset/quiet-timers-rest.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@tanstack/query-core': patch
3+
---
4+
5+
Do not schedule garbage collection on the server. A timer scheduled during server rendering captures the async context it was created in and keeps that whole render alive until it fires, while the client it would clean up is dropped with the response. Only queries and mutations with an explicit finite `gcTime` were affected, since the server default is already `Infinity`.

packages/query-core/src/__tests__/query.test.tsx

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
QueryObserver,
1313
dehydrate,
1414
hydrate,
15+
timeoutManager,
1516
} from '..'
1617
import { hashQueryKeyByOptions } from '../utils'
1718
import { mockOnlineManagerIsOnline, setIsServer } from './utils'
@@ -983,6 +984,25 @@ describe('query', () => {
983984
}
984985
})
985986

987+
it('should not schedule garbage collection on the server, even with an explicit gcTime', () => {
988+
const resetIsServer = setIsServer(true)
989+
const scheduled = vi.spyOn(timeoutManager, 'setTimeout')
990+
991+
try {
992+
const query = queryCache.build(queryClient, {
993+
queryKey: queryKey(),
994+
queryFn: () => 'data',
995+
gcTime: 1000,
996+
})
997+
998+
expect(query.gcTime).toBe(1000)
999+
expect(scheduled).not.toHaveBeenCalled()
1000+
} finally {
1001+
scheduled.mockRestore()
1002+
resetIsServer()
1003+
}
1004+
})
1005+
9861006
it('constructor should call initialDataUpdatedAt if defined as a function', async () => {
9871007
const key = queryKey()
9881008

packages/query-core/src/removable.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,10 @@ export abstract class Removable {
1414
protected scheduleGc(): void {
1515
this.clearGcTimeout()
1616

17+
if (isServerEnvironment()) {
18+
return
19+
}
20+
1721
if (isValidTimeout(this.gcTime)) {
1822
this.#gcTimeout = timeoutManager.setTimeout(() => {
1923
this.optionalRemove()

0 commit comments

Comments
 (0)