TanStackT
TanStack2y ago
24 replies
progressive-amaranth

Prevent same component from unmounting between routes

I have these three routes:
* /search/
* /search/$query
* /search/$query/$section

All of these routes render my <SearchIndex /> component with a query and section props if those params are available. In our react-router@v3 setup the component stays mounted between routes if both routes render the same component, but I notice that TanStack Router re-mounts the component each time the matched route changes, which is causing weird state issues and preventing us from doing the transitions we want.

Is it possible for the component to stay mounted in between route changes, if the component each route renders is the same but the props differ?

// search.index.tsx
export const Route = createFileRoute('/search/')({
  component: () => <SearchIndex />,
})

// search.$query.tsx
export const Route = createFileRoute('/search/$query')({
  component: SearchQueryRoute,
})
function SearchQueryRoute() {
  const { query } = Route.useParams()
  return <SearchIndex query={query} />
}

// search.$query.$section.tsx
export const Route = createFileRoute('/search/$query/$section')({
  component: SearchQueryRoute,
})
function SearchQueryRoute() {
  const { query, section } = Route.useParams()
  return <SearchIndex query={query} section={section} />
}
Was this page helpful?