Skip to content

Conversation

@longfellowone
Copy link
Contributor

@longfellowone longfellowone commented Dec 23, 2025

Summary

Fixes #6195

Fixes HMR (Hot Module Replacement) not updating the UI when route components are defined as inline arrow functions. This regression appeared around v1.128.3 (worked in v1.128.0).

Problem

When a route uses an inline arrow function for its component option (common in file-based routing), React Refresh cannot register the component for HMR updates. The router's HMR handler compensates by calling router.invalidate() to trigger updates, but the MatchInner component's useRouterState selector did not include the invalid field. This meant React didn't detect any state change and didn't re-render, so the UI stayed on the old component even though HMR was triggered.

Named function components still work because React Refresh can register them directly, bypassing this issue.

Solution

Add invalid: match.invalid to the MatchInner component's useRouterState selector. This ensures React detects the state change when invalidate() is called and re-renders the component tree, picking up the new component reference.

Changes

  • packages/react-router/src/Match.tsx: Add invalid to the selector (1 line)
  • packages/react-router/tests/router.test.tsx: Add regression test that:
    • Renders component v1
    • Swaps to component v2 (simulating HMR)
    • Calls invalidate()
    • Verifies new component v2 is rendered

Test plan

  • Verified test fails without fix (shows "Version 1" after swap)
  • Verified test passes with fix (shows "Version 2" after swap)
  • All 816 existing tests pass
  • Manually tested HMR in examples/react/basic-file-based with inline arrow function

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • The match object now exposes an invalid property for improved routing state visibility.
  • Tests

    • Added regression tests simulating development invalidation to confirm swapped components render correctly.
    • Added tests verifying render and loader invocation counts during invalidation with and without async loaders to ensure minimal, correct re-renders.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 23, 2025

Walkthrough

Adds an invalid property (sourced from router state) to the match object returned by the selector in MatchInnerImpl, and adds HMR/invalidate tests that mutate route components and call router.invalidate() to verify updated rendering and render counts.

Changes

Cohort / File(s) Summary
Core match selector
packages/react-router/src/Match.tsx
Selector now includes invalid on the returned match object alongside id, status, error, _forcePending, and _displayPending.
HMR & invalidate tests
packages/react-router/tests/router.test.tsx
Expands the invalidate test suite with HMR-like tests that mutate route.options.component, call router.invalidate(), and assert UI updates and render counts for inline components and loader-driven components (including async loader scenarios).

Sequence Diagram(s)

(omitted)

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Suggested reviewers

  • schiller-manuel
  • brenelz

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title accurately reflects the main fix: adding the invalid property to the selector so HMR can detect state changes and update inline arrow function components.
Linked Issues check ✅ Passed The code changes fully address issue #6195 by including the invalid field in the selector, enabling HMR detection for component updates. Regression tests verify the fix works for both inline and loader-driven components.
Out of Scope Changes check ✅ Passed All changes are directly scoped to fixing HMR for inline arrow function components: one-line selector fix and regression tests simulating HMR scenarios.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

📜 Recent review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a0b0996 and 4b3f06e.

📒 Files selected for processing (1)
  • packages/react-router/tests/router.test.tsx
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Use TypeScript strict mode with extensive type safety for all code

Files:

  • packages/react-router/tests/router.test.tsx
**/*.{js,ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Implement ESLint rules for router best practices using the ESLint plugin router

Files:

  • packages/react-router/tests/router.test.tsx
🧠 Learnings (5)
📓 Common learnings
Learnt from: nlynzaad
Repo: TanStack/router PR: 5402
File: packages/router-generator/tests/generator/no-formatted-route-tree/routeTree.nonnested.snapshot.ts:19-21
Timestamp: 2025-10-08T08:11:47.088Z
Learning: Test snapshot files in the router-generator tests directory (e.g., files matching the pattern `packages/router-generator/tests/generator/**/routeTree*.snapshot.ts` or `routeTree*.snapshot.js`) should not be modified or have issues flagged, as they are fixtures used to verify the generator's output and are intentionally preserved as-is.
📚 Learning: 2025-10-08T08:11:47.088Z
Learnt from: nlynzaad
Repo: TanStack/router PR: 5402
File: packages/router-generator/tests/generator/no-formatted-route-tree/routeTree.nonnested.snapshot.ts:19-21
Timestamp: 2025-10-08T08:11:47.088Z
Learning: Test snapshot files in the router-generator tests directory (e.g., files matching the pattern `packages/router-generator/tests/generator/**/routeTree*.snapshot.ts` or `routeTree*.snapshot.js`) should not be modified or have issues flagged, as they are fixtures used to verify the generator's output and are intentionally preserved as-is.

Applied to files:

  • packages/react-router/tests/router.test.tsx
📚 Learning: 2025-12-06T15:03:07.223Z
Learnt from: CR
Repo: TanStack/router PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-06T15:03:07.223Z
Learning: Applies to **/*.{js,ts,tsx} : Implement ESLint rules for router best practices using the ESLint plugin router

Applied to files:

  • packages/react-router/tests/router.test.tsx
📚 Learning: 2025-10-01T18:30:26.591Z
Learnt from: schiller-manuel
Repo: TanStack/router PR: 5330
File: packages/router-core/src/router.ts:2231-2245
Timestamp: 2025-10-01T18:30:26.591Z
Learning: In `packages/router-core/src/router.ts`, the `resolveRedirect` method intentionally strips the router's origin from redirect URLs when they match (e.g., `https://foo.com/bar` → `/bar` for same-origin redirects) while preserving the full URL for cross-origin redirects. This logic should not be removed or simplified to use `location.publicHref` directly.

Applied to files:

  • packages/react-router/tests/router.test.tsx
📚 Learning: 2025-10-14T18:59:33.990Z
Learnt from: FatahChan
Repo: TanStack/router PR: 5475
File: e2e/react-start/basic-prerendering/src/routes/redirect/$target/via-beforeLoad.tsx:8-0
Timestamp: 2025-10-14T18:59:33.990Z
Learning: In TanStack Router e2e test files, when a route parameter is validated at the route level (e.g., using zod in validateSearch or param validation), switch statements on that parameter do not require a default case, as the validation ensures only expected values will reach the switch.

Applied to files:

  • packages/react-router/tests/router.test.tsx

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@nx-cloud
Copy link

nx-cloud bot commented Dec 23, 2025

View your CI Pipeline Execution ↗ for commit 4b3f06e

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

☁️ Nx Cloud last updated this comment at 2025-12-23 08:58:20 UTC

@pkg-pr-new
Copy link

pkg-pr-new bot commented Dec 23, 2025

More templates

@tanstack/arktype-adapter

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

@tanstack/directive-functions-plugin

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

@tanstack/eslint-plugin-router

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

@tanstack/history

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

@tanstack/nitro-v2-vite-plugin

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

@tanstack/react-router

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

@tanstack/react-router-devtools

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

@tanstack/react-router-ssr-query

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

@tanstack/react-start

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

@tanstack/react-start-client

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

@tanstack/react-start-server

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

@tanstack/router-cli

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

@tanstack/router-core

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

@tanstack/router-devtools

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

@tanstack/router-devtools-core

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

@tanstack/router-generator

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

@tanstack/router-plugin

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

@tanstack/router-ssr-query-core

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

@tanstack/router-utils

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

@tanstack/router-vite-plugin

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

@tanstack/server-functions-plugin

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

@tanstack/solid-router

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

@tanstack/solid-router-devtools

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

@tanstack/solid-router-ssr-query

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

@tanstack/solid-start

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

@tanstack/solid-start-client

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

@tanstack/solid-start-server

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

@tanstack/start-client-core

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

@tanstack/start-fn-stubs

npm i https://pkg.pr.new/TanStack/router/@tanstack/start-fn-stubs@6197

@tanstack/start-plugin-core

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

@tanstack/start-server-core

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

@tanstack/start-static-server-functions

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

@tanstack/start-storage-context

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

@tanstack/valibot-adapter

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

@tanstack/virtual-file-routes

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

@tanstack/vue-router

npm i https://pkg.pr.new/TanStack/router/@tanstack/vue-router@6197

@tanstack/vue-router-devtools

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

@tanstack/vue-router-ssr-query

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

@tanstack/vue-start

npm i https://pkg.pr.new/TanStack/router/@tanstack/vue-start@6197

@tanstack/vue-start-client

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

@tanstack/vue-start-server

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

@tanstack/zod-adapter

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

commit: 4b3f06e

@schiller-manuel
Copy link
Contributor

how often is the new component then rendered then after invalidation?
should only be rendered once.

@longfellowone longfellowone force-pushed the fix/hmr-inline-arrow-components branch 2 times, most recently from 345acb4 to 2add982 Compare December 23, 2025 07:58
@longfellowone
Copy link
Contributor Author

The component renders exactly once after invalidate().

I've added two render count verification tests that prove this:

  • renders minimal times after invalidate without loader - asserts exactly 1 render
  • renders minimal times after invalidate with async loader - asserts exactly 1 render (loader also called once)

The tests track render calls across the component swap and verify only 1 render occurs after invalidate(). React's automatic batching handles the invalid: false→true→false transitions efficiently.

You can see the test output in CI or run locally:

pnpm test:unit --run -t "render count verification"

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: 2

📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 345acb4 and 2add982.

📒 Files selected for processing (2)
  • packages/react-router/src/Match.tsx
  • packages/react-router/tests/router.test.tsx
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Use TypeScript strict mode with extensive type safety for all code

Files:

  • packages/react-router/tests/router.test.tsx
  • packages/react-router/src/Match.tsx
**/*.{js,ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Implement ESLint rules for router best practices using the ESLint plugin router

Files:

  • packages/react-router/tests/router.test.tsx
  • packages/react-router/src/Match.tsx
🧠 Learnings (5)
📓 Common learnings
Learnt from: nlynzaad
Repo: TanStack/router PR: 5402
File: packages/router-generator/tests/generator/no-formatted-route-tree/routeTree.nonnested.snapshot.ts:19-21
Timestamp: 2025-10-08T08:11:47.088Z
Learning: Test snapshot files in the router-generator tests directory (e.g., files matching the pattern `packages/router-generator/tests/generator/**/routeTree*.snapshot.ts` or `routeTree*.snapshot.js`) should not be modified or have issues flagged, as they are fixtures used to verify the generator's output and are intentionally preserved as-is.
📚 Learning: 2025-10-08T08:11:47.088Z
Learnt from: nlynzaad
Repo: TanStack/router PR: 5402
File: packages/router-generator/tests/generator/no-formatted-route-tree/routeTree.nonnested.snapshot.ts:19-21
Timestamp: 2025-10-08T08:11:47.088Z
Learning: Test snapshot files in the router-generator tests directory (e.g., files matching the pattern `packages/router-generator/tests/generator/**/routeTree*.snapshot.ts` or `routeTree*.snapshot.js`) should not be modified or have issues flagged, as they are fixtures used to verify the generator's output and are intentionally preserved as-is.

Applied to files:

  • packages/react-router/tests/router.test.tsx
📚 Learning: 2025-12-06T15:03:07.223Z
Learnt from: CR
Repo: TanStack/router PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-12-06T15:03:07.223Z
Learning: Applies to **/*.{js,ts,tsx} : Implement ESLint rules for router best practices using the ESLint plugin router

Applied to files:

  • packages/react-router/tests/router.test.tsx
📚 Learning: 2025-10-14T18:59:33.990Z
Learnt from: FatahChan
Repo: TanStack/router PR: 5475
File: e2e/react-start/basic-prerendering/src/routes/redirect/$target/via-beforeLoad.tsx:8-0
Timestamp: 2025-10-14T18:59:33.990Z
Learning: In TanStack Router e2e test files, when a route parameter is validated at the route level (e.g., using zod in validateSearch or param validation), switch statements on that parameter do not require a default case, as the validation ensures only expected values will reach the switch.

Applied to files:

  • packages/react-router/tests/router.test.tsx
📚 Learning: 2025-10-01T18:30:26.591Z
Learnt from: schiller-manuel
Repo: TanStack/router PR: 5330
File: packages/router-core/src/router.ts:2231-2245
Timestamp: 2025-10-01T18:30:26.591Z
Learning: In `packages/router-core/src/router.ts`, the `resolveRedirect` method intentionally strips the router's origin from redirect URLs when they match (e.g., `https://foo.com/bar` → `/bar` for same-origin redirects) while preserving the full URL for cross-origin redirects. This logic should not be removed or simplified to use `location.publicHref` directly.

Applied to files:

  • packages/react-router/tests/router.test.tsx
🔇 Additional comments (2)
packages/react-router/src/Match.tsx (1)

213-213: LGTM! Critical fix for HMR with inline arrow function components.

Including invalid in the useRouterState selector ensures React detects state changes when router.invalidate() is called, triggering the necessary re-render to display updated components during HMR.

packages/react-router/tests/router.test.tsx (1)

1490-1551: LGTM! Excellent regression test for HMR with inline arrow functions.

This test correctly simulates the HMR scenario by swapping the component reference and calling invalidate(), then verifying the updated component renders. The comprehensive documentation explains the issue and test strategy clearly.

Comment on lines 1604 to 1609
console.log('[No loader] Initial renders:', initialCallCount)
console.log('[No loader] Renders after invalidate:', rendersAfterInvalidate)
console.log('[No loader] Render calls:', renderTracker.mock.calls)

// We expect exactly 1 render to pick up new component
expect(rendersAfterInvalidate).toBe(1)
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Remove console.log statements from test code.

The debugging console.log statements (lines 1604-1606) should be removed to keep test output clean.

🔎 Proposed fix
-    // Log for debugging
-    console.log('[No loader] Initial renders:', initialCallCount)
-    console.log('[No loader] Renders after invalidate:', rendersAfterInvalidate)
-    console.log('[No loader] Render calls:', renderTracker.mock.calls)
-
     // We expect exactly 1 render to pick up new component
     expect(rendersAfterInvalidate).toBe(1)

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In packages/react-router/tests/router.test.tsx around lines 1604 to 1609, remove
the three debugging console.log statements on lines 1604–1606 (the '[No loader]
Initial renders', '[No loader] Renders after invalidate', and '[No loader]
Render calls' logs) so the test output remains clean and keep the subsequent
expectation (expect(rendersAfterInvalidate).toBe(1)) intact; run the test suite
to confirm no regressions.

Comment on lines 1665 to 1674
console.log('[With loader] Initial renders:', initialCallCount)
console.log('[With loader] Renders after invalidate:', rendersAfterInvalidate)
console.log('[With loader] Loader calls after invalidate:', loaderCallsAfterInvalidate)
console.log('[With loader] Render calls:', renderTracker.mock.calls)

// Loader should be called once
expect(loaderCallsAfterInvalidate).toBe(1)
// Component should render at most 2 times (once for invalidation, possibly once for load complete)
expect(rendersAfterInvalidate).toBeGreaterThanOrEqual(1)
expect(rendersAfterInvalidate).toBeLessThanOrEqual(2)
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Remove console.log statements from test code.

The debugging console.log statements (lines 1665-1668) should be removed to keep test output clean. The render count assertions (1-2 renders with async loader) are reasonable given the async loading lifecycle.

🔎 Proposed fix
-    console.log('[With loader] Initial renders:', initialCallCount)
-    console.log('[With loader] Renders after invalidate:', rendersAfterInvalidate)
-    console.log('[With loader] Loader calls after invalidate:', loaderCallsAfterInvalidate)
-    console.log('[With loader] Render calls:', renderTracker.mock.calls)
-
     // Loader should be called once
     expect(loaderCallsAfterInvalidate).toBe(1)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
console.log('[With loader] Initial renders:', initialCallCount)
console.log('[With loader] Renders after invalidate:', rendersAfterInvalidate)
console.log('[With loader] Loader calls after invalidate:', loaderCallsAfterInvalidate)
console.log('[With loader] Render calls:', renderTracker.mock.calls)
// Loader should be called once
expect(loaderCallsAfterInvalidate).toBe(1)
// Component should render at most 2 times (once for invalidation, possibly once for load complete)
expect(rendersAfterInvalidate).toBeGreaterThanOrEqual(1)
expect(rendersAfterInvalidate).toBeLessThanOrEqual(2)
// Loader should be called once
expect(loaderCallsAfterInvalidate).toBe(1)
// Component should render at most 2 times (once for invalidation, possibly once for load complete)
expect(rendersAfterInvalidate).toBeGreaterThanOrEqual(1)
expect(rendersAfterInvalidate).toBeLessThanOrEqual(2)
🤖 Prompt for AI Agents
In packages/react-router/tests/router.test.tsx around lines 1665 to 1674, remove
the four console.log debugging lines that print render/loader counts (the lines
beginning with console.log('[With loader] ...')), leaving only the assertions;
this keeps test output clean while preserving the existing loader/render
assertions and test behavior.

@schiller-manuel
Copy link
Contributor

please remove the console logs

When a route uses an inline arrow function for its component (common in
file-based routing), React Refresh cannot register the component for
HMR updates. The router's HMR handler calls router.invalidate() to
trigger updates, but the MatchInner component's useRouterState selector
did not include the 'invalid' field, so React didn't detect the state
change and didn't re-render.

This fix adds 'invalid: match.invalid' to the selector, ensuring React
detects the state change when invalidate() is called and re-renders the
component tree, picking up the new component reference.

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

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
@longfellowone longfellowone force-pushed the fix/hmr-inline-arrow-components branch from 485fc06 to fee6467 Compare December 23, 2025 08:06
@schiller-manuel
Copy link
Contributor

about the async loader test: component does not consume the loader data, so it shouldn't rerender because of loader finishing. please modify the test to consume the loader data and also let the loader return new data the second time. then check if new component has new loader data

longfellowone and others added 2 commits December 23, 2025 00:29
Per reviewer feedback, the async loader test now:
- Consumes loader data via useLoaderData()
- Loader returns different data each call (loaded-1 → loaded-2)
- Verifies new component receives new loader data
- Expects 2 renders (1 for invalidation, 1 for new data)

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

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
@schiller-manuel schiller-manuel merged commit b1c7350 into TanStack:main Dec 23, 2025
6 checks passed
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.

HMR updates not applied for __root.tsx changes (requires full reload)

2 participants