Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

useLocation re-renders before navigating #3110

Open
Sheraff opened this issue Jan 4, 2025 · 0 comments
Open

useLocation re-renders before navigating #3110

Sheraff opened this issue Jan 4, 2025 · 0 comments

Comments

@Sheraff
Copy link

Sheraff commented Jan 4, 2025

Which project does this relate to?

Router

Describe the bug

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

Your Example Website or App

https://stackblitz.com/edit/tanstack-router-fpv611d5?file=src%2Froutes%2F_yo%2Fabout.tsx

Steps to Reproduce the Bug or Issue

  1. Go to '/about' in the demo above
  2. open the console to see what gets logged
  3. Go to any other page

This will show that the console.log(pathname) (similar to the one in the code sample above) logs the next route even though it's only in the route component of /about.

The about.tsx file contains other commented-out methods of "logging the pathname" that demonstrate the various render behaviors.

Expected behavior

I'm not entirely sure what is "expected behavior" here. But my naive intuition would be that for all of these methods, since they're used inside the "/about" route, they should only ever render with the "/about" pathname.

Screenshots or Videos

Screen.Recording.2025-01-04.at.16.43.05.mov

Platform

  • OS: macOS
  • Browser: Chrome
  • Version: 1.95.0

Additional context

This might be the same behavior that causes #2318 because their demo uses

    const location = useLocation();
          <ErrorBoundary
            resetKeys={[location.pathname]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant