Skip to content

Conversation

Sheraff
Copy link
Contributor

@Sheraff Sheraff commented Aug 23, 2025

Add a few more setup configurations to measure the number of __store updates:

  • with caching (staleTime > 0)
  • when preloading multiple times the same route (simulates hovering a list of links to the same page w/ different params)

Copy link
Contributor

coderabbitai bot commented Aug 23, 2025

Walkthrough

Adds new router options defaultStaleTime/defaultGcTime to createRouter, updates test scaffolding/UI for navigation, introduces a back() helper, parameterizes staleTime in setup, and expands tests to cover preloading and loader behavior with revised update-count expectations.

Changes

Cohort / File(s) Summary
Tests: Store updates during navigation
packages/react-router/tests/store-updates-during-navigation.test.tsx
Accepts defaultStaleTime/defaultGcTime in router setup; adds Back/Posts links in Root; simplifies Index component; introduces back() helper; parameterizes staleTime; adds/adjusts tests for preloading and loader types; updates expected update counts.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor U as User
  participant R as Router
  participant C as Cache
  participant L as Loader

  Note over R,C: Router created with defaultStaleTime/defaultGcTime
  U->>R: Navigate to /posts (optionally preload beforehand)
  alt Preloaded & fresh
    R->>C: Check entry (fresh)
    C-->>R: Serve cached data
    R-->>U: Render with minimal updates
  else Preloaded but stale
    R->>C: Check entry (stale)
    R->>L: Revalidate/Load
    L-->>R: Data
    R->>C: Update entry (respect gcTime)
    R-->>U: Render with updates
  else Not preloaded
    R->>L: Load
    L-->>R: Data
    R->>C: Put entry (staleTime/gcTime)
    R-->>U: Render
  end

  U->>R: Back
  R-->>U: Render previous route (Index)
  Note over C: GC respects defaultGcTime
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • schiller-manuel

Poem

Thump-thump goes my rabbit heart,
New stale clocks tick, caches smart.
Back we hop, then forward glide,
Preloads waiting, side by side.
Tests now count each tiny leap—
Updates fewer, burrows deep. 🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch test-react-router-store-updates-more-variants

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

nx-cloud bot commented Aug 23, 2025

View your CI Pipeline Execution ↗ for commit 6521321

Command Status Duration Result
nx affected --targets=test:eslint,test:unit,tes... ✅ Succeeded 1m 42s View ↗
nx run-many --target=build --exclude=examples/*... ✅ Succeeded 1s View ↗

☁️ Nx Cloud last updated this comment at 2025-08-23 14:21:14 UTC

Copy link

pkg-pr-new bot commented Aug 23, 2025

More templates

@tanstack/arktype-adapter

npm i https://pkg.pr.new/TanStack/router/@tanstack/arktype-adapter@5019

@tanstack/directive-functions-plugin

npm i https://pkg.pr.new/TanStack/router/@tanstack/directive-functions-plugin@5019

@tanstack/eslint-plugin-router

npm i https://pkg.pr.new/TanStack/router/@tanstack/eslint-plugin-router@5019

@tanstack/history

npm i https://pkg.pr.new/TanStack/router/@tanstack/history@5019

@tanstack/react-router

npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router@5019

@tanstack/react-router-devtools

npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router-devtools@5019

@tanstack/react-router-ssr-query

npm i https://pkg.pr.new/TanStack/router/@tanstack/react-router-ssr-query@5019

@tanstack/react-start

npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start@5019

@tanstack/react-start-client

npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-client@5019

@tanstack/react-start-plugin

npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-plugin@5019

@tanstack/react-start-server

npm i https://pkg.pr.new/TanStack/router/@tanstack/react-start-server@5019

@tanstack/router-cli

npm i https://pkg.pr.new/TanStack/router/@tanstack/router-cli@5019

@tanstack/router-core

npm i https://pkg.pr.new/TanStack/router/@tanstack/router-core@5019

@tanstack/router-devtools

npm i https://pkg.pr.new/TanStack/router/@tanstack/router-devtools@5019

@tanstack/router-devtools-core

npm i https://pkg.pr.new/TanStack/router/@tanstack/router-devtools-core@5019

@tanstack/router-generator

npm i https://pkg.pr.new/TanStack/router/@tanstack/router-generator@5019

@tanstack/router-plugin

npm i https://pkg.pr.new/TanStack/router/@tanstack/router-plugin@5019

@tanstack/router-ssr-query-core

npm i https://pkg.pr.new/TanStack/router/@tanstack/router-ssr-query-core@5019

@tanstack/router-utils

npm i https://pkg.pr.new/TanStack/router/@tanstack/router-utils@5019

@tanstack/router-vite-plugin

npm i https://pkg.pr.new/TanStack/router/@tanstack/router-vite-plugin@5019

@tanstack/server-functions-plugin

npm i https://pkg.pr.new/TanStack/router/@tanstack/server-functions-plugin@5019

@tanstack/solid-router

npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-router@5019

@tanstack/solid-router-devtools

npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-router-devtools@5019

@tanstack/solid-start

npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start@5019

@tanstack/solid-start-client

npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-client@5019

@tanstack/solid-start-plugin

npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-plugin@5019

@tanstack/solid-start-server

npm i https://pkg.pr.new/TanStack/router/@tanstack/solid-start-server@5019

@tanstack/start-client-core

npm i https://pkg.pr.new/TanStack/router/@tanstack/start-client-core@5019

@tanstack/start-plugin-core

npm i https://pkg.pr.new/TanStack/router/@tanstack/start-plugin-core@5019

@tanstack/start-server-core

npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-core@5019

@tanstack/start-server-functions-client

npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-functions-client@5019

@tanstack/start-server-functions-fetcher

npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-functions-fetcher@5019

@tanstack/start-server-functions-server

npm i https://pkg.pr.new/TanStack/router/@tanstack/start-server-functions-server@5019

@tanstack/start-storage-context

npm i https://pkg.pr.new/TanStack/router/@tanstack/start-storage-context@5019

@tanstack/valibot-adapter

npm i https://pkg.pr.new/TanStack/router/@tanstack/valibot-adapter@5019

@tanstack/virtual-file-routes

npm i https://pkg.pr.new/TanStack/router/@tanstack/virtual-file-routes@5019

@tanstack/zod-adapter

npm i https://pkg.pr.new/TanStack/router/@tanstack/zod-adapter@5019

commit: 6521321

@Sheraff Sheraff merged commit 9cc216b into main Aug 23, 2025
5 of 6 checks passed
@Sheraff Sheraff deleted the test-react-router-store-updates-more-variants branch August 23, 2025 14:26
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (6)
packages/react-router/tests/store-updates-during-navigation.test.tsx (6)

98-106: Prefer userEvent for clicks to better emulate user input

FireEvent works, but userEvent is closer to real interactions and can reduce edge cases with focus/blur sequencing.

Apply this minimal tweak:

-  const link = await waitFor(() => screen.getByRole('link', { name: 'Back' }))
-  fireEvent.click(link)
+  const link = await waitFor(() => screen.getByRole('link', { name: 'Back' }))
+  await userEvent.click(link)

Add the import (outside this hunk):

import userEvent from '@testing-library/user-event'

229-243: Strengthen the assertion by verifying the preload actually removed a loader call

Great coverage. To ensure preloading is truly leveraged, assert that the loader ran only once across preload + navigation.

-    const params = setup({
-      beforeLoad: () => Promise.resolve({ foo: 'bar' }),
-      loader: () => resolveAfter(100, { hello: 'world' }),
+    const loaderSpy = vi.fn(() => resolveAfter(100, { hello: 'world' }))
+    const params = setup({
+      beforeLoad: () => Promise.resolve({ foo: 'bar' }),
+      loader: loaderSpy,
       staleTime: 1000,
     })
 
     await params.router.preloadRoute({ to: '/posts' })
     const updates = await run(params)
 
     // This number should be as small as possible to minimize the amount of work
     // that needs to be done during a navigation.
     // Any change that increases this number should be investigated.
     expect(updates).toBe(7)
+    expect(loaderSpy).toHaveBeenCalledTimes(1)

245-259: Same strengthening for sync loaders

Even with sync loaders, asserting a single call validates reuse of preloaded data.

-    const params = setup({
-      beforeLoad: () => ({ foo: 'bar' }),
-      loader: () => ({ hello: 'world' }),
+    const loaderSpy = vi.fn(() => ({ hello: 'world' }))
+    const params = setup({
+      beforeLoad: () => ({ foo: 'bar' }),
+      loader: loaderSpy,
       staleTime: 1000,
     })
 
     await params.router.preloadRoute({ to: '/posts' })
     const updates = await run(params)
 
     expect(updates).toBe(6)
+    expect(loaderSpy).toHaveBeenCalledTimes(1)

261-275: Leverage a spy to guarantee no second load within stale window

The update count already indicates caching; adding a loader call assertion reduces brittleness.

-    const params = setup({
-      loader: () => resolveAfter(100, { hello: 'world' }),
+    const loaderSpy = vi.fn(() => resolveAfter(100, { hello: 'world' }))
+    const params = setup({
+      loader: loaderSpy,
       staleTime: 1000,
     })
 
     await run(params)
     await back()
     const updates = await run(params)
 
     expect(updates).toBe(5)
+    expect(loaderSpy).toHaveBeenCalledTimes(1)

277-293: Stabilize timing: replace real timers with fake timers for deterministic preload/preload

Using real setTimeout(20) can be flaky under load. Fake timers make this race deterministic.

   test('preload a preloaded route w/ async loader', async () => {
-    const params = setup({
-      loader: () => resolveAfter(100, { hello: 'world' }),
-    })
+    vi.useFakeTimers()
+    const params = setup({
+      loader: () => resolveAfter(100, { hello: 'world' }),
+    })
 
     await params.router.preloadRoute({ to: '/posts' })
-    await new Promise((r) => setTimeout(r, 20))
+    vi.advanceTimersByTime(20)
     const before = params.select.mock.calls.length
     await params.router.preloadRoute({ to: '/posts' })
     const after = params.select.mock.calls.length
     const updates = after - before
 
     // This number should be as small as possible to minimize the amount of work
     // that needs to be done during a navigation.
     // Any change that increases this number should be investigated.
     expect(updates).toBe(1)
+    vi.useRealTimers()
   })

121-123: Return the resolved value from resolveAfter with correct typing

Current signature returns Promise<void> while resolving a value. Generics keep types accurate and self-document intent.

-function resolveAfter(ms: number, value: any) {
-  return new Promise<void>((resolve) => setTimeout(() => resolve(value), ms))
-}
+function resolveAfter<T>(ms: number, value: T): Promise<T> {
+  return new Promise<T>((resolve) => setTimeout(() => resolve(value), ms))
+}
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 40f9ab7 and 6521321.

📒 Files selected for processing (1)
  • packages/react-router/tests/store-updates-during-navigation.test.tsx (4 hunks)
🔇 Additional comments (4)
packages/react-router/tests/store-updates-during-navigation.test.tsx (4)

50-56: Root scaffolding looks good; stable anchor points for interactions

Adding explicit Back/Posts links and keeping Outlet visible makes the tests clearer and interactions deterministic.


62-62: Simplified Index component is appropriate

Lean markup helps reduce unrelated DOM updates during these measurements.


228-228: Non-functional whitespace change

No action needed.


34-35: Make defaultStaleTime/defaultGcTime opt-in and confirm public API acceptance

Using a conditional spread ensures you only override the defaults when a staleTime value is provided, preserving the built-in defaults otherwise:

-    defaultStaleTime: staleTime,
-    defaultGcTime: staleTime,
+    ...(staleTime != null
+      ? { defaultStaleTime: staleTime, defaultGcTime: staleTime }
+      : {}),

Verified in packages/router-core/src/router.ts that both

  • defaultStaleTime? (line 197)
  • defaultGcTime? (line 245)

are declared on the public RouterOptions interface, and the router’s constructor options extend this interface, so these fields are accepted by createRouter. Please apply this pattern at the other occurrences (lines 43–44 and 89–91).

tannerlinsley pushed a commit that referenced this pull request Aug 30, 2025
Add a few more setup configurations to measure the number of `__store`
updates:
- with caching (`staleTime > 0`)
- when preloading multiple times the same route (simulates hovering a
list of links to the same page w/ different params)

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant