import { useEffect, useState } from "react"; const initHistoryPatch = (() => { let initialized = false; return () => { if (initialized) return; initialized = true; const patch = (method: "pushState" | "replaceState") => { const original = history[method]; history[method] = function (...args) { const result = original.apply(this, args); window.dispatchEvent(new Event("locationchange")); return result; }; }; patch("pushState"); patch("replaceState"); }; })(); export const usePathname = () => { const [pathname, setPathname] = useState(""); useEffect(() => { initHistoryPatch(); const update = () => { queueMicrotask(() => setPathname(window.location.pathname)); }; window.addEventListener("popstate", update); window.addEventListener("locationchange", update); return () => { window.removeEventListener("popstate", update); window.removeEventListener("locationchange", update); }; }, []); return pathname; };