next js 13 router.events how to do it? #56256
Replies: 3 comments 1 reply
-
Same question here, We need to close a menu when the user has navigated to another router, but there is no easy way to do it. |
Beta Was this translation helpful? Give feedback.
-
Also looking for an answer to this, though I think the answer is that we can't yet for the app router. I want the Does someone from Vercel have a workaround or a timeline on when this (hopefully) is going to be added? |
Beta Was this translation helpful? Give feedback.
-
I wrote a workaround for this. Created an event emitter and wrapped it in a hook: // hooks/useOnRouteChange.ts
import EventEmitter from "events";
import { usePathname } from "next/navigation";
import { useEffect } from "react";
const emitter = new EventEmitter();
export const useOnRouteChange = (cb: () => void) => {
const url = usePathname();
useEffect(() => {
emitter.once("routeChange", cb);
}, [cb]);
useEffect(() => {
emitter.emit("routeChange");
}, [url]);
return emitter;
}; and then use it like this in a component: export const MobileMenu: FC<IMobileMenu> = () => {
const [isOpen, setIsOpen] = useState(false);
useOnRouteChange(() => setIsOpen(false))
return (
...
)
} |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
how to do it in next js 13
Beta Was this translation helpful? Give feedback.
All reactions