TanStackT
TanStack13mo ago
4 replies
brilliant-lime

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>
  );
}

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 });

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 });


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)
Was this page helpful?