Describe the bug#
When setQueries replaces its queries with different ones, the previous set are not garbage collected when the cache removes them. Specifically, the listener closure keeps prevObservers.
In our React app, this was via useQueries.
The previous queries' state.data stays in memory until a later setQueries call subscribes new observers and drops the ones the previous call subscribed.
Memory was also freed when the QueriesObserver unsubscribes (via a key prop in the React component)
With large query results this can hold a lot of memory. We noticed with Chrome tabs crashing with OOM after about 1.7 GB of rows from ~50 previous queries remained after the gcTime had passed.
Your minimal, reproducible example#
https://gist.github.com/duncanhope/73592df1f320ba55a4fd8233367f1a5c
Steps to reproduce#
git clone https://gist.github.com/73592df1f320ba55a4fd8233367f1a5c.git repro && cd repro
npm install
npm start
setQueries swaps the queries on one observer
remount instead creates a new QueriesObserver (i.e. mimicking what a remount or key change in React does)
Both cases then remove the old queries, force a GC, and count how many of them are still alive
with setQueries, both are still alive:
with remount, both freed:
```remount: 0 of 2 removed queries still alive (0 means freed)```
### Expected behavior
As a user, I'm expecting setQueries to stop holding queries so they can be gc'd without the need for a remount
### How often does this bug happen?
Every time
### Screenshots or Videos
_No response_
### Platform
Linux
Node 26.12.0
also seen in Chrome 158
### Tanstack Query adapter
vanilla
### TanStack Query version
v5.108.2
### TypeScript version
_No response_
### Additional context
local patch involved creating the listeners in a separate method so the closure doesn't capture prevObservers. onSubscribe used that same method
with it the gist repro showed 0 of 2 alive on 5.108.2
happy to raise a PR with a regression test, or just provide code
I can reproduce this with your gist on 5.108.2. The subscribe callbacks created inside the setQueries batch callback and in onSubscribe close over the observer list, which keeps prevObservers (and their queries) reachable - your listener-extraction approach looks like the right fix. Happy to turn it into a PR with a regression test if you'd rather not; if you're already working on one, I'll step back.