TL;DR
packages/stx/src/reactivity.ts:451-458 implements watch(source, callback, options) so that when source is a getter function (vs a ref/signal), it kicks off a setInterval(check, 16). Combined with options.deep (lines 422-430), each tick runs JSON.stringify(newValue) !== JSON.stringify(oldValue) then JSON.parse(JSON.stringify(newValue)) to clone the previous value. For a moderately deep object this is O(n) per tick at 60fps.
Why this is bad
- Wakes the event loop continuously, even when nothing in the page is changing. Browsers can't idle the tab.
- JSON-based comparison misses several update kinds: doesn't fire on
+0vs-0, onNaN→NaN, dropsundefinedproperties, drops functions, loses Map/Set membership. So you pay the cost AND can miss real updates. - JSON-based clone breaks circular refs, Date, RegExp, typed arrays, Map, Set, class instances. Anything more structured than POJO + primitives is silently mishandled.
- The 16ms cadence is hardcoded — there's no debounce, no
requestIdleCallback, no opt-out.
This sits inside reactivity.ts's Vue-compat layer, so the typical user reaching it has just written:
watch(() => store.items.length, (n) => render(n))…not realizing the function-source path is the slow branch. The signal-source path (watch(myCount, …)) is correct and reactive.
Proposed direction
The right model is to evaluate the source function inside the reactive graph (same way derived() does — track signal reads, re-fire on change). That eliminates polling entirely. The function-source watch() should desugar to:
function watch(source, callback, opts) {
if (typeof source === 'function') {
let prev = source()
effect(() => {
const next = source() // tracks signal reads inside
if (!sameValue(next, prev, opts.deep)) {
callback(next, prev)
prev = opts.deep ? structuredClone(next) : next
}
})
} else {
// ref / signal source — existing path
}
}That makes watch(() => store.items.length, …) behave the same as derived(() => store.items.length).subscribe(…) — no polling, fires only when an actually-tracked signal changes.
Other fixes worth bundling:
- Replace
JSON.stringify-based deep equality withObject.isfor primitives + recursive structural comparison for objects (or use a vetted library). - Replace
JSON.parse(JSON.stringify(...))deep-clone withstructuredClone(native, handles cyclic refs, Maps, Sets, dates).
Severity
Real perf hit at scale; mitigated by the fact that signal-source watch() (the common path) is fine. Function-source watch() is the common Vue-migration pattern, so the moment users adopt Vue-compat APIs they likely hit this.
Found during a deep-scan audit.
🤖 Filed via Claude Code