Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/empty-olives-melt.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@tanstack/react-router': patch
---

Perf improvement of useMatch and derived hooks when navigating away from previous match
28 changes: 15 additions & 13 deletions packages/react-router/src/useMatch.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -179,21 +179,23 @@ export function useMatch<
useStructuralSharing(opts, router)

// eslint-disable-next-line react-hooks/rules-of-hooks -- condition is static
return useStore(matchStore ?? dummyStore, (match) => {
if (!match) {
if (opts.shouldThrow ?? true) {
if (process.env.NODE_ENV !== 'production') {
throw new Error(
`Invariant failed: Could not find ${opts.from ? `an active match from "${opts.from}"` : 'a nearest match!'}`,
)
}
const matchSelection = useStore(matchStore ?? dummyStore, (match) =>
match ? selector(match as any) : dummyStore,
)

invariant()
}
if (matchSelection !== dummyStore) {
return matchSelection
}

return undefined
if (opts.shouldThrow ?? true) {
if (process.env.NODE_ENV !== 'production') {
throw new Error(
`Invariant failed: Could not find ${opts.from ? `an active match from "${opts.from}"` : 'a nearest match!'}`,
)
}

return selector(match as any)
}) as any
invariant()
}

return undefined as any
}
18 changes: 18 additions & 0 deletions packages/react-router/tests/useMatch.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,24 @@ describe('useMatch', () => {
expect(postsTitle).toBeInTheDocument()
},
)

test('returns undefined from select when match is found', async () => {
const select = vi.fn(() => undefined)

function RootComponent() {
const match = useMatch({ from: '/posts', select })
expect(match).toBeUndefined()
return <Outlet />
}

setup({
RootComponent,
history: createMemoryHistory({ initialEntries: ['/posts'] }),
})
const postsTitle = await screen.findByText('PostsTitle')
expect(postsTitle).toBeInTheDocument()
expect(select).toHaveBeenCalled()
})
})

describe('when match is not found', () => {
Expand Down
Loading