[query-core] [performances] `setQueryData` dispatches a `success` event (and triggers broadcast/persist) even when the new data is structurally identical to the cached data
维护者通常 1 天内回复
评估
- 难度
- 4/5
- 预计耗时
- 3-5 天
- 新手友好度
- 52/100
- Issue 类型
- 功能
- 描述清晰度
- 描述清楚
- 活跃度
- 活跃
- 技术栈
- typescript
调研方向
Start by reading setData and replaceData in the query core, then trace how setQueryData and setQueriesData call them. Check the tests covering manual cache writes, cache events, and explicit updatedAt values. Done means structurally identical manual writes can skip success events while explicit timestamp updates and fetch writes retain their intended behavior.
由索引模型根据 Issue 内容生成。
描述
Describe the bug
queryClient.setQueryData always writes the new data through Query#setData, which dispatches a success cache event, increments state.dataUpdateCount and refreshes timestamps — even when the new data is structurally identical to what is already cached.
Since v5, setData already runs a deep comparison on every write for structural sharing (replaceData), so the equality is already computed — but it is only used to preserve references, not to skip the write.
Minimal repro (no framework needed, @tanstack/query-core 5.105.0):
import { QueryClient } from '@tanstack/query-core';
const client = new QueryClient();
let events = 0;
client.getQueryCache().subscribe((cacheEvent) => {
if (cacheEvent.type === 'event' && cacheEvent.event.type === 'success') events++;
});
const base = { id: '1', name: 'item', meta: { tag: 'a', n: 1 } };
client.setQueryData(['item', '1'], base);
// Same content, new reference — the typical upsert pattern used by cache-sync helpers:
for (let i = 0; i < 10; i++) {
client.setQueryData(['item', '1'], (old) => ({ ...old, ...JSON.parse(JSON.stringify(base)) }));
}
console.log(events); // 11 — ten extra 'success' events for data that never changed
console.log(client.getQueryCache().find({ queryKey: ['item', '1'] })!.state.dataUpdateCount); // 11
Expected: a manual write whose result is structurally identical to the current data should not dispatch a cache event (or at least should be able to).
Why it matters
The no-op write is invisible to components — because the structural-sharing result is referentially identical to the old data, observers do not re-render — so the cost never shows up as a visible bug. But every dispatched success event is still fully processed by:
@tanstack/query-broadcast-client-experimental— on everysuccessevent it structured-clones the query's full state and posts it on the channel.@tanstack/query-persist-client-corewith manualpersistQueryByKey(the pattern recommended for manual cache updates, see #6310) — every call writes the full state to storage, and an IndexedDBputstructured-clones its value synchronously on the main thread.
So an application that upserts a parent entity plus its N children into the cache per page transition (a common normalized-cache pattern) pays N state clones + N cross-tab posts per transition even when nothing changed.
Measured in an application with that pattern (one page transition entering an edit form that upserts ~10 cached entities, warm cache):
| no guard | no-op skip | |
|---|---|---|
success events dispatched |
609 | 193 |
| full-state writes to IndexedDB | 218 | 16 |
The 416 / 202 eliminated operations were all structurally no-op writes. (We currently work around this at the application level with a deep-equality pre-check in a setQueryData wrapper plus a persistQueryByKey dedup keyed on dataUpdateCount; an in-library fix would cover all call sites at once.)
Suggested fix
setData already computes the shared result, and when the whole tree is structurally identical, replaceData returns the previous reference itself — so the short-circuit is a zero-cost reference comparison:
setData(newData, options) {
const data = replaceData(this.state.data, newData, this.options);
if (options?.manual && data === this.state.data) return data; // no-op manual write: skip the dispatch
this.#dispatch({ data, type: 'success', dataUpdatedAt: options?.updatedAt, manual: options?.manual });
return data;
}
Scoping to manual: true (writes from setQueryData / setQueriesData) leaves the fetch path untouched.
Behavior change to flag
dataUpdatedAt/dataUpdateCountwould not bump on a skipped no-op write. For manual writes this seems correct (nothing was updated), but it is an observable change.- A call that passes an explicit
updatedAtoption should probably still dispatch, since the caller explicitly asked for a timestamp change.
Versions
"@tanstack/eslint-plugin-query": "5.105.0",
"@tanstack/query-broadcast-client-experimental": "5.105.0",
"@tanstack/query-persist-client-core": "5.105.0",
"@tanstack/svelte-query": "6.3.6",
"@tanstack/svelte-query-devtools": "6.3.6",
- 主要语言
- TypeScript
- 星标
- 50.5k
- 派生
- 4.2k
- 平均合并
- 7 小时 24 分钟
- 30 天内合并 PR
- 570
环境准备
- 没有 Dockerfile 或 Docker Compose 文件
- 有 Pull Request 模板
- 阅读贡献指南
从这里开始
- 先读完整个 Issue,再读项目的贡献指南。
- 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
- Fork 仓库,在一个分支上完成修改。
- 提交 Pull Request,并在描述里引用这个 Issue 编号。
TanStack/query 的其他 Issue
-
solid-query 6.0.0-rc.5: useBaseQuery bumps its version signal on observerAdded/observerRemoved, remounting <Show> children in a loop on Solid 2 rc.14+可能已有人在做 关联的 PR 仍在进行中或已合并。 未关闭
难度 2/5 1-3 小时 新手友好度 78/100
维护者通常 1 天内回复
-
solid-query: STRICT_READ_UNTRACKED on Solid 2 — client()/options() read in component body (useMutation, useBaseQuery)可能重新可做 @LeonxLJX 于 58 天前认领,目前没有进行中的 PR。 未关闭
难度 2/5 1-3 小时 新手友好度 84/100
TanStack/query#11358 · 2 条评论 · 1 个 reaction ·
维护者通常 1 天内回复
-
refetchQueries with throwOnError leaves paused fetch rejection unhandled on client.clear()可能已有人在做 @lazerg 于 3 天前认领。 未关闭
难度 3/5 1-2 天 新手友好度 67/100
维护者通常 1 天内回复
-
useBaseQuery fetches the old query key when an <Activity> tree is revealed可能已有人在做 @lazerg 于 11 天前认领。 未关闭
难度 3/5 1-2 天 新手友好度 35/100
维护者通常 1 天内回复
-
[query-broadcast-client-experimental] broadcastQueryClient: an `added` event overwrites a receiving query that has no data (e.g. in error) with the sender's empty state可能已有人在做 @lazerg 于 11 天前认领。 未关闭
难度 2/5 1-3 小时 新手友好度 25/100
维护者通常 1 天内回复
相似的 Issue
-
clawsweeper:fix-shape-clear clawsweeper:queueable-fix clawsweeper:source-repro impact:auth-provider issue-rating: 🦞 diamond lobster no-stale P1
难度 2/5 1-3 小时 新手友好度 70/100
steipete/oracle#614 · 1 条评论 · 1 个 reaction ·
维护者通常 1 天内回复
-
难度 2/5 1-3 小时 新手友好度 70/100
Koenkk/zigbee-herdsman-converters#13656 ·
维护者通常 2 天内回复
-
check:passed streams:remove
难度 1/5 1 小时以内 新手友好度 62/100
维护者通常 1 天内回复
-
难度 1/5 1 小时以内 新手友好度 88/100
维护者通常 1 天内回复
-
bug needs triage
难度 2/5 1-3 小时 新手友好度 62/100
actions/setup-node#1659 ·
维护者通常 1 天内回复