Skip to content

Commit ad3ab7f

Browse files
authored
refactor(router-core): unify replaceEqualDeep implementation w/ query (#5067)
Following TanStack/query#9604, this PR replicates the implementation of `replaceEqualDeep` here, so that both are more similar (avoid drifting apart over time). There are no performance changes. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - Performance - Optimized internal deep-compare and replacement logic to short-circuit equal values and avoid unnecessary recursion, improving route state updates. Users may see faster navigations and reduced CPU usage in complex scenarios. - Refactor - Simplified internal implementation while preserving existing behavior and public APIs. No functional changes or breaking changes for consumers. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
1 parent 5b5f792 commit ad3ab7f

File tree

1 file changed

+19
-13
lines changed

1 file changed

+19
-13
lines changed

packages/router-core/src/utils.ts

Lines changed: 19 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -217,9 +217,8 @@ export function replaceEqualDeep<T>(prev: any, _next: T): T {
217217
const next = _next as any
218218

219219
const array = isPlainArray(prev) && isPlainArray(next)
220-
const object = !array && isPlainObject(prev) && isPlainObject(next)
221220

222-
if (!array && !object) return next
221+
if (!array && !(isPlainObject(prev) && isPlainObject(next))) return next
223222

224223
const prevItems = array ? prev : getEnumerableOwnKeys(prev)
225224
if (!prevItems) return next
@@ -234,20 +233,27 @@ export function replaceEqualDeep<T>(prev: any, _next: T): T {
234233
for (let i = 0; i < nextSize; i++) {
235234
const key = array ? i : (nextItems[i] as any)
236235
const p = prev[key]
236+
const n = next[key]
237+
238+
if (p === n) {
239+
copy[key] = p
240+
if (array ? i < prevSize : prev.hasOwnProperty(key)) equalItems++
241+
continue
242+
}
243+
237244
if (
238-
(array || prev.hasOwnProperty(key)) &&
239-
p === undefined &&
240-
next[key] === undefined
245+
p === null ||
246+
n === null ||
247+
typeof p !== 'object' ||
248+
typeof n !== 'object'
241249
) {
242-
copy[key] = undefined
243-
equalItems++
244-
} else {
245-
const value = replaceEqualDeep(p, next[key])
246-
copy[key] = value
247-
if (value === p && p !== undefined) {
248-
equalItems++
249-
}
250+
copy[key] = n
251+
continue
250252
}
253+
254+
const v = replaceEqualDeep(p, n)
255+
copy[key] = v
256+
if (v === p) equalItems++
251257
}
252258

253259
return prevSize === nextSize && equalItems === prevSize ? prev : copy

0 commit comments

Comments
 (0)