0
Fork 0
mirror of https://github.com/TanStack/router.git synced 2026-11-16 19:38:07 +00:00

fix: prevent stale head() re-runs from polluting state

Problem:
When async loaders complete, we schedule a detached head() re-run to
execute head functions with fresh loaderData. However, if a new navigation
or invalidation starts before this re-run executes, it would update state
with stale data.

The previous location-based check only caught navigation to different
locations, but missed same-location invalidations (e.g., manual reload,
scheduled refetch).

Solution:
Implement a generation counter pattern to track load operations:

1. Add `router._loadGeneration` counter (excludes preloads)
2. Each non-preload `loadMatches()` call increments the counter
3. Store the generation in `inner.loadGeneration` when load starts
4. Before executing head re-runs or updates, check if generation matches

This detects ALL cases where a load has been superseded:
- Navigation to different location (new loadMatches call)
- Invalidation on same location (new loadMatches call)
- Any other scenario triggering a new load

The generation counter is a standard pattern in reactive systems (React,
RxJS) for detecting stale computations. Benefits:
- No circular references (vs storing full context)
- Minimal memory (4 bytes)
- Simple numeric comparison
- Clear semantics (higher = newer)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
yanghuidong 2025-12-29 18:13:49 +08:00
commit 3d51361651
2 changed files with 62 additions and 6 deletions