Skip to content

Commit 68f4530

Browse files
fix: don't re-execute stale loaders on unrelated location changes
1 parent 88fcbec commit 68f4530

15 files changed

Lines changed: 280 additions & 83 deletions

File tree

‎docs/router/api/router/RouterType.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -159,7 +159,7 @@ Remove cached route matches.
159159
160160
Loads all of the currently matched route matches and resolves when they are all loaded and ready to be rendered.
161161
162-
> ⚠️⚠️⚠️ **`router.load()` respects `route.staleTime` and will not forcefully reload a route match if it is still fresh. If you need to forcefully reload a route match, use `router.invalidate()` instead.**
162+
> ⚠️⚠️⚠️ **`router.load()` respects `route.staleTime`: fresh matches stay fresh, but stale matches are revalidated even if their loader key did not change. If you need to forcefully reload all active matches regardless of freshness, use `router.invalidate()` instead.**
163163
164164
- Type: `(opts?: {sync?: boolean}) => Promise<void>`
165165
- if `sync` is true, the promise returned by this function will only resolve once all loaders have finished.

‎docs/router/guide/data-loading.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -154,7 +154,7 @@ To control router dependencies and "freshness", TanStack Router provides a pleth
154154

155155
### ⚠️ Some Important Defaults
156156

157-
- By default, the `staleTime` is set to `0`, meaning that the route's data will always be considered stale and will always be reloaded in the background when the route is rematched.
157+
- By default, the `staleTime` is set to `0`, meaning that the route's data is immediately considered stale. Stale matches are reloaded in the background when the route is entered again, when its loader key changes (path params used by the route or `loaderDeps`), or when `router.load()` is called explicitly.
158158
- By default, a previously preloaded route is considered fresh for **30 seconds**. This means if a route is preloaded, then preloaded again within 30 seconds, the second preload will be ignored. This prevents unnecessary preloads from happening too frequently. **When a route is loaded normally, the standard `staleTime` is used.**
159159
- By default, the `gcTime` is set to **30 minutes**, meaning that any route data that has not been accessed in 30 minutes will be garbage collected and removed from the cache.
160160
- `router.invalidate()` will force all active routes to reload their loaders immediately and mark every cached route's data as stale.
@@ -201,7 +201,7 @@ export const Route = createFileRoute('/posts')({
201201
202202
### Using `staleTime` to control how long data is considered fresh
203203
204-
By default, `staleTime` for navigations is set to `0`ms (and 30 seconds for preloads) which means that the route's data will always be considered stale and will always be reloaded in the background when the route is matched and navigated to.
204+
By default, `staleTime` for navigations is set to `0`ms (and 30 seconds for preloads) which means that the route's data will always be considered stale. When a stale route is entered again, its loader key changes, or `router.load()` is called explicitly, the route will reload in the background.
205205
206206
**This is a good default for most use cases, but you may find that some route data is more static or potentially expensive to load.** In these cases, you can use the `staleTime` option to control how long the route's data is considered fresh for navigations. Let's take a look at an example:
207207

‎packages/react-router/src/fileRoute.ts‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import { useSearch } from './useSearch'
88
import { useParams } from './useParams'
99
import { useNavigate } from './useNavigate'
1010
import { useRouter } from './useRouter'
11+
import { useRouteContext } from './useRouteContext'
1112
import type { UseParamsRoute } from './useParams'
1213
import type { UseMatchRoute } from './useMatch'
1314
import type { UseSearchRoute } from './useSearch'
@@ -229,10 +230,7 @@ export class LazyRoute<TRoute extends AnyRoute> {
229230
}
230231

231232
useRouteContext: UseRouteContextRoute<TRoute['id']> = (opts) => {
232-
return useMatch({
233-
from: this.options.id,
234-
select: (d: any) => (opts?.select ? opts.select(d.context) : d.context),
235-
}) as any
233+
return useRouteContext({ from: this.options.id, ...(opts as any) }) as any
236234
}
237235

238236
useSearch: UseSearchRoute<TRoute['id']> = (opts) => {

‎packages/react-router/src/route.tsx‎

Lines changed: 4 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ import { useParams } from './useParams'
1111
import { useSearch } from './useSearch'
1212
import { useNavigate } from './useNavigate'
1313
import { useMatch } from './useMatch'
14+
import { useRouteContext } from './useRouteContext'
1415
import { useRouter } from './useRouter'
1516
import { Link } from './link'
1617
import type {
@@ -114,10 +115,7 @@ export class RouteApi<
114115
}
115116

116117
useRouteContext: UseRouteContextRoute<TId> = (opts) => {
117-
return useMatch({
118-
from: this.id as any,
119-
select: (d) => (opts?.select ? opts.select(d.context) : d.context),
120-
}) as any
118+
return useRouteContext({ from: this.id as any, ...(opts as any) }) as any
121119
}
122120

123121
useSearch: UseSearchRoute<TId> = (opts) => {
@@ -272,11 +270,7 @@ export class Route<
272270
}
273271

274272
useRouteContext: UseRouteContextRoute<TId> = (opts?) => {
275-
return useMatch({
276-
...opts,
277-
from: this.id,
278-
select: (d) => (opts?.select ? opts.select(d.context) : d.context),
279-
}) as any
273+
return useRouteContext({ from: this.id, ...(opts as any) }) as any
280274
}
281275

282276
useSearch: UseSearchRoute<TId> = (opts) => {
@@ -548,11 +542,7 @@ export class RootRoute<
548542
}
549543

550544
useRouteContext: UseRouteContextRoute<RootRouteId> = (opts) => {
551-
return useMatch({
552-
...opts,
553-
from: this.id,
554-
select: (d) => (opts?.select ? opts.select(d.context) : d.context),
555-
}) as any
545+
return useRouteContext({ from: this.id, ...(opts as any) }) as any
556546
}
557547

558548
useSearch: UseSearchRoute<RootRouteId> = (opts) => {

‎packages/react-router/tests/store-updates-during-navigation.test.tsx‎

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -136,7 +136,7 @@ describe("Store doesn't update *too many* times during navigation", () => {
136136
// This number should be as small as possible to minimize the amount of work
137137
// that needs to be done during a navigation.
138138
// Any change that increases this number should be investigated.
139-
expect(updates).toBeGreaterThanOrEqual(10) // WARN: this is flaky, and sometimes (rarely) is 12
139+
expect(updates).toBeGreaterThanOrEqual(9) // WARN: this is flaky, and sometimes (rarely) is 12
140140
expect(updates).toBeLessThanOrEqual(13)
141141
})
142142

@@ -155,7 +155,7 @@ describe("Store doesn't update *too many* times during navigation", () => {
155155
// This number should be as small as possible to minimize the amount of work
156156
// that needs to be done during a navigation.
157157
// Any change that increases this number should be investigated.
158-
expect(updates).toBe(4)
158+
expect(updates).toBe(5)
159159
})
160160

161161
test('sync beforeLoad', async () => {
@@ -171,7 +171,7 @@ describe("Store doesn't update *too many* times during navigation", () => {
171171
// This number should be as small as possible to minimize the amount of work
172172
// that needs to be done during a navigation.
173173
// Any change that increases this number should be investigated.
174-
expect(updates).toBeGreaterThanOrEqual(9) // WARN: this is flaky
174+
expect(updates).toBeGreaterThanOrEqual(8) // WARN: this is flaky
175175
expect(updates).toBeLessThanOrEqual(12)
176176
})
177177

@@ -183,7 +183,7 @@ describe("Store doesn't update *too many* times during navigation", () => {
183183
// This number should be as small as possible to minimize the amount of work
184184
// that needs to be done during a navigation.
185185
// Any change that increases this number should be investigated.
186-
expect(updates).toBeGreaterThanOrEqual(6) // WARN: this is flaky, and sometimes (rarely) is 9
186+
expect(updates).toBeGreaterThanOrEqual(5) // WARN: this is flaky, and sometimes (rarely) is 9
187187
expect(updates).toBeLessThanOrEqual(9)
188188
})
189189

@@ -241,8 +241,8 @@ describe("Store doesn't update *too many* times during navigation", () => {
241241
// This number should be as small as possible to minimize the amount of work
242242
// that needs to be done during a navigation.
243243
// Any change that increases this number should be investigated.
244-
expect(updates).toBeGreaterThanOrEqual(7)
245-
expect(updates).toBeLessThanOrEqual(8)
244+
expect(updates).toBeGreaterThanOrEqual(8)
245+
expect(updates).toBeLessThanOrEqual(9)
246246
})
247247

248248
test('navigate, w/ preloaded & sync loaders', async () => {
@@ -258,7 +258,7 @@ describe("Store doesn't update *too many* times during navigation", () => {
258258
// This number should be as small as possible to minimize the amount of work
259259
// that needs to be done during a navigation.
260260
// Any change that increases this number should be investigated.
261-
expect(updates).toBe(6)
261+
expect(updates).toBe(8)
262262
})
263263

264264
test('navigate, w/ previous navigation & async loader', async () => {
@@ -274,7 +274,7 @@ describe("Store doesn't update *too many* times during navigation", () => {
274274
// This number should be as small as possible to minimize the amount of work
275275
// that needs to be done during a navigation.
276276
// Any change that increases this number should be investigated.
277-
expect(updates).toBe(5)
277+
expect(updates).toBe(7)
278278
})
279279

280280
test('preload a preloaded route w/ async loader', async () => {
@@ -292,6 +292,6 @@ describe("Store doesn't update *too many* times during navigation", () => {
292292
// This number should be as small as possible to minimize the amount of work
293293
// that needs to be done during a navigation.
294294
// Any change that increases this number should be investigated.
295-
expect(updates).toBe(1)
295+
expect(updates).toBe(2)
296296
})
297297
})

‎packages/router-core/src/Matches.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,8 @@ export interface RouteMatch<
143143
/** @internal */
144144
loaderPromise?: ControlledPromise<void>
145145
/** @internal */
146+
loaderKeyChanged?: boolean
147+
/** @internal */
146148
pendingTimeout?: ReturnType<typeof setTimeout>
147149
loadPromise?: ControlledPromise<void>
148150
displayPendingPromise?: Promise<void>

‎packages/router-core/src/load-matches.ts‎

Lines changed: 50 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ type InnerLoadContext = {
3333
updateMatch: UpdateMatchFn
3434
matches: Array<AnyRouteMatch>
3535
preload?: boolean
36+
forceStaleReload?: boolean
3637
onReady?: () => Promise<void>
3738
sync?: boolean
3839
}
@@ -166,7 +167,10 @@ const shouldSkipLoader = (
166167
inner: InnerLoadContext,
167168
matchId: string,
168169
): boolean => {
169-
const match = inner.router.getMatch(matchId)!
170+
const match = inner.router.getMatch(matchId)
171+
if (!match) {
172+
return true
173+
}
170174
// upon hydration, we skip the loader if the match has been dehydrated on the server
171175
if (!(isServer ?? inner.router.isServer) && match._nonReactive.dehydrated) {
172176
return true
@@ -179,6 +183,36 @@ const shouldSkipLoader = (
179183
return false
180184
}
181185

186+
const shouldReloadStaleMatch = (
187+
inner: InnerLoadContext,
188+
match: AnyRouteMatch,
189+
): boolean => {
190+
if (inner.forceStaleReload) {
191+
return true
192+
}
193+
194+
if (match.cause === 'enter') {
195+
return true
196+
}
197+
198+
return !!match._nonReactive.loaderKeyChanged
199+
}
200+
201+
const syncMatchContext = (
202+
inner: InnerLoadContext,
203+
matchId: string,
204+
index: number,
205+
): void => {
206+
const nextContext = buildMatchContext(inner, index)
207+
208+
inner.updateMatch(matchId, (prev) => {
209+
return {
210+
...prev,
211+
context: nextContext,
212+
}
213+
})
214+
}
215+
182216
const handleSerialError = (
183217
inner: InnerLoadContext,
184218
index: number,
@@ -479,8 +513,6 @@ const executeBeforeLoad = (
479513

480514
batch(() => {
481515
pending()
482-
// Only store __beforeLoadContext here, don't update context yet
483-
// Context will be updated in loadRouteMatch after loader completes
484516
inner.updateMatch(matchId, (prev) => ({
485517
...prev,
486518
__beforeLoadContext: beforeLoadContext,
@@ -787,8 +819,11 @@ const loadRouteMatch = async (
787819

788820
// If the route is successful and still fresh, just resolve
789821
const { status, invalid } = match
822+
const staleMatchShouldReload =
823+
age > staleAge && shouldReloadStaleMatch(inner, match)
790824
loaderShouldRunAsync =
791-
status === 'success' && (invalid || (shouldReload ?? age > staleAge))
825+
status === 'success' &&
826+
(invalid || (shouldReload ?? staleMatchShouldReload))
792827
if (preload && route.options.preload === false) {
793828
// Do nothing
794829
} else if (loaderShouldRunAsync && !inner.sync) {
@@ -808,6 +843,8 @@ const loadRouteMatch = async (
808843
})()
809844
} else if (status !== 'success' || (loaderShouldRunAsync && inner.sync)) {
810845
await runLoader(inner, matchPromises, matchId, index, route)
846+
} else {
847+
syncMatchContext(inner, matchId, index)
811848
}
812849
}
813850

@@ -817,8 +854,15 @@ const loadRouteMatch = async (
817854
const route = inner.router.looseRoutesById[routeId]!
818855

819856
if (shouldSkipLoader(inner, matchId)) {
857+
const match = inner.router.getMatch(matchId)
858+
if (!match) {
859+
return inner.matches[index]!
860+
}
861+
862+
syncMatchContext(inner, matchId, index)
863+
820864
if (isServer ?? inner.router.isServer) {
821-
return inner.router.getMatch(matchId)!
865+
return match
822866
}
823867
} else {
824868
const prevMatch = inner.router.getMatch(matchId)! // This is where all of the stale-while-revalidate magic happens
@@ -886,6 +930,7 @@ export async function loadMatches(arg: {
886930
location: ParsedLocation
887931
matches: Array<AnyRouteMatch>
888932
preload?: boolean
933+
forceStaleReload?: boolean
889934
onReady?: () => Promise<void>
890935
updateMatch: UpdateMatchFn
891936
sync?: boolean

‎packages/router-core/src/router.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1513,6 +1513,9 @@ export class RouterCore<
15131513
const existingMatch = this.getMatch(matchId)
15141514

15151515
const previousMatch = previousMatchesByRouteId.get(route.id)
1516+
const loaderKeyChanged = previousMatch
1517+
? previousMatch.id !== matchId
1518+
: false
15161519

15171520
const strictParams = existingMatch?._strictParams ?? usedParams
15181521

@@ -1545,6 +1548,10 @@ export class RouterCore<
15451548
if (existingMatch) {
15461549
match = {
15471550
...existingMatch,
1551+
_nonReactive: {
1552+
...existingMatch._nonReactive,
1553+
loaderKeyChanged,
1554+
},
15481555
cause,
15491556
params: previousMatch?.params ?? routeParams,
15501557
_strictParams: strictParams,
@@ -1583,6 +1590,7 @@ export class RouterCore<
15831590
__routeContext: undefined,
15841591
_nonReactive: {
15851592
loadPromise: createControlledPromise(),
1593+
loaderKeyChanged,
15861594
},
15871595
__beforeLoadContext: undefined,
15881596
context: {},
@@ -2364,6 +2372,7 @@ export class RouterCore<
23642372
let redirect: AnyRedirect | undefined
23652373
let notFound: NotFoundError | undefined
23662374
let loadPromise: Promise<void>
2375+
const previousLocation = this.state.resolvedLocation ?? this.state.location
23672376

23682377
// eslint-disable-next-line prefer-const
23692378
loadPromise = new Promise<void>((resolve) => {
@@ -2394,6 +2403,7 @@ export class RouterCore<
23942403
await loadMatches({
23952404
router: this,
23962405
sync: opts?.sync,
2406+
forceStaleReload: previousLocation.href === next.href,
23972407
matches: this.state.pendingMatches as Array<AnyRouteMatch>,
23982408
location: next,
23992409
updateMatch: this.updateMatch,

0 commit comments

Comments
 (0)