T
TanStack7mo ago
initial-rose

Router invalidate and context

We are looking at this one issue where router context gets stale and we need to call .invalidate to keep it fresh. Our auth is ran by Clerk so we want to grab the user and auth state whenever the session tokens have been changed. This setup works but its causing a very annoying "jump to top of page" whenever the context is refreshed. I may have missed something in the docs somewhere so im asking here, has anyone done anything similar or would happen to think of a better approach? I cant provide a repro but ill share the code for it so if anyone by chance uses Clerk or is willing to try it out they should be able to. This is just a react+vite setup with Clerk react (not using tanstack start)
function App() {
const user = useUser()
const authenticated = useAuth()
const authContext = useMemo(() => {
return {
user,
authenticated,
}
}, [
user,
authenticated,
])

useEffect(() => {
router.invalidate()
}, [authContext])

return (
<>
<RouterProvider router={router} defaultPreload="intent" context={{ auth: authContext }} />
</>
)
}
function App() {
const user = useUser()
const authenticated = useAuth()
const authContext = useMemo(() => {
return {
user,
authenticated,
}
}, [
user,
authenticated,
])

useEffect(() => {
router.invalidate()
}, [authContext])

return (
<>
<RouterProvider router={router} defaultPreload="intent" context={{ auth: authContext }} />
</>
)
}
10 Replies
metropolitan-bronze
metropolitan-bronze7mo ago
invalidating triggers scroll to top? should be an easy fix can you open a GitHub issue please?
initial-rose
initial-roseOP7mo ago
@Manuel Schiller Will do! Im not gonna say 100% that its the only cause but removing my invalidations on the effect here at least solves the jumping but breaks the rest. This I should be able to make a reproduction of.
metropolitan-bronze
metropolitan-bronze7mo ago
a reproducer on stackblitz would help
initial-rose
initial-roseOP7mo ago
Sorry! This turns out to be a bug that was. We were running on 1.104.1 and it is in fact fixed in the latest.
metropolitan-bronze
metropolitan-bronze7mo ago
nice! i was wondering about that since I have fix a few things lately 😄
initial-rose
initial-roseOP7mo ago
I made the repro and then it dawned on me to check what our version was. Glad its fixed and thanks for those 😄
metropolitan-bronze
metropolitan-bronze7mo ago
cool
extended-salmon
extended-salmon7mo ago
Stupid question . Is the memo needed? Can’t you just pass user,authenticated as deps to effect?
initial-rose
initial-roseOP7mo ago
@Mihai Andrei You would be right, they do not need to be memoed here. But it would not make any difference in this case 👍
extended-salmon
extended-salmon7mo ago
Yea. I agree. It wouldn’t make a difference. Was trying to learn a bit of the use case of useMemo. Thank you!

Did you find this page helpful?