T
TanStack9mo ago
equal-aqua

Why does `useLocation` re-render before navigation?

Assuming a simple route like this:
export const Route = createFileRoute('/about')({
component: AboutComponent,
});

function AboutComponent() {
const {pathname} = useLocation()
console.log(pathname)
return (
<div className="p-2">
<h3>About</h3>
</div>
);
}
export const Route = createFileRoute('/about')({
component: AboutComponent,
});

function AboutComponent() {
const {pathname} = useLocation()
console.log(pathname)
return (
<div className="p-2">
<h3>About</h3>
</div>
);
}
My naive assumption would be that the only value pathname can ever have here is "/about", but in reality, this will also re-render just before navigating away, with pathname having the value of the next page. Alternatively, we can also use the following:
const pathname = useRouterState({ select: (s) => s.resolvedLocation.pathname });
const pathname = useRouterState({ select: (s) => s.resolvedLocation.pathname });
But in that case, pathname will initially have the value of the previous page before immediately re-rendering with the current page. One way to access the pathname that seems stable is this:
const pathname = useMatch({ strict: false, select: (s) => s.pathname });
const pathname = useMatch({ strict: false, select: (s) => s.pathname });
Coming from react-router-dom, I have a couple questions: - why do these APIs behave differently? I'm expecting the answer is along the lines of "X behaves like this because it's the internal state of the router, but Y behaves like this because..." - what is the purpose of those different behaviors? something like "you should use X in situation A, but Y when you need B" (Here's a demo of these behaviors for anyone interested: https://stackblitz.com/edit/tanstack-router-fpv611d5?file=src%2Froutes%2F_yo%2Fabout.tsx)
4 Replies
jolly-crimson
jolly-crimson9mo ago
probably best to create a GitHub issue for this
equal-aqua
equal-aquaOP9mo ago
ah you think this is an issue? I though it was just my mental model that wasn't adapted to tanstack/router. I can make an issue then
jolly-crimson
jolly-crimson9mo ago
not sure really
equal-aqua
equal-aquaOP9mo ago
GitHub
useLocation re-renders before navigating · Issue #3110 · TanStack...
Which project does this relate to? Router Describe the bug Assuming a simple route like this: export const Route = createFileRoute('/about')({ component: AboutComponent, }); function AboutC...

Did you find this page helpful?