Search code examples
reactjsnext.jsreact-hooksnext-router

Next.js 13 router methods do not exist. How to cause a state change when routing


Methods that previously existed in next/router don't seem to work with next 13 (latest). I get a mounting issue if I use anything from next/router, so it's suggested to use next/navigation per docs.

https://nextjs.org/docs/messages/next-router-not-mounted

next/navigation does not have all the functionality next router did, even when i alias next/router, i still cant use any of it per the mounting issue.

I'm just trying to close a component that renders a div when I navigate to another page within the app, but listeners or history or events.on/events.off don't seem to work.

I've set the state to false in various places, all it is is a show/hide boolean, but i cant hide when navigating.

another example of a method that doesnt exist in next/navigation.

useRouter().onBeforeUnmount(() => {
  handleRouteChange();
});

Any help would be appreciated.

Here is a similar issue, but this is dated and doesnt work with latest next as I cannot use next/router ? Changing state on route change Next.js


Solution

  • The router from next/router is not initialized inside the app directory as you have already correctly noticed yourself.

    "use client";
    
    import { useEffect } from "react";
    import { usePathname } from "next/navigation";
    
    interface Props {
      onChange: (pathname: string) => void;
    }
    
    export default function PathTracker({ onChange }: Props) {
      const pathname = usePathname();
      useEffect(() => onChange(pathname), [pathname]);
      return <></>;
    }
    

    As seen in the example I have provided above, you can use the usePathname hook to determine any change in the current path.