Next.js Discord

Discord Forum

useRouter next/navigation how to do shallow routing?

Unanswered
Asian black bear posted this in #help-forum
Open in Discord
Asian black bearOP
I am trying to use useRouter from next/navigation within page router to do incremental migration. however, I am struggling to do shallow routing with router.push and router.replace. is there a direct replacement that I can use? thanks!

8 Replies

Asian black bearOP
useParams, usePathname seem useful so I started using them in the page router. not sure if this is ideal
Asian black bearOP
I think that only works in the app router right?
if you use the pages router you should use next/router instead of next/navigation
Asian black bearOP
Gotcha. how about the other hooks such as useParams, usePathname? would it be fine to use those in page router? seems like they are supported
any reasons you don't use useRouter().query and useRouter().pathname?
Asian black bearOP
I can. There are components that might be used in both app and page router during the migration so I was trying to see if it was possible to update those components to use these hooks first
@Asian black bear I can. There are components that might be used in both app and page router during the migration so I was trying to see if it was possible to update those components to use these hooks first
ah yes for router-agnostic hooks, useParams and usePathname work. i don't know if the window.history method works in the pages router as well, but it probably does work there.

if it doesn't work there, you can use this hook to check whether you are in the app router or the pages router and execute useRouter().push(..., { shallow: true }) or window.history.pushState(...) accordingly:

// not next/router here!
import { useRouter } from "next/compat/router";

export function useIsAppRouter() {
  // it returns the router instance if it is rendered in the pages router
  // returns null if it is in the app router
  const router = useRouter();
  return !router;
}