import { useSyncExternalStore } from "react"; interface LocationState { href?: string; pathname?: string; search?: string; hash?: string; host?: string; hostname?: string; port?: string; protocol?: string; origin?: string; } let listeners: Array<() => void> = []; let currentSnapshot: LocationState | undefined = undefined; function updateSnapshot() { if (typeof window === "undefined") { currentSnapshot = undefined; return; } currentSnapshot = { href: window.location.href, pathname: window.location.pathname, search: window.location.search, hash: window.location.hash, host: window.location.host, hostname: window.location.hostname, port: window.location.port, protocol: window.location.protocol, origin: window.location.origin, }; } // Initialize snapshot updateSnapshot(); function subscribe(callback: () => void) { listeners.push(callback); if (typeof window === "undefined") { return () => { listeners = listeners.filter((l) => l !== callback); }; } const notifyListeners = () => { updateSnapshot(); listeners.forEach((listener) => listener()); }; // Listen to navigation events window.addEventListener("popstate", notifyListeners); window.addEventListener("hashchange", notifyListeners); // Intercept pushState and replaceState const originalPushState = window.history.pushState; const originalReplaceState = window.history.replaceState; window.history.pushState = function (...args) { originalPushState.apply(window.history, args); notifyListeners(); }; window.history.replaceState = function (...args) { originalReplaceState.apply(window.history, args); notifyListeners(); }; return () => { listeners = listeners.filter((l) => l !== callback); window.removeEventListener("popstate", notifyListeners); window.removeEventListener("hashchange", notifyListeners); // Restore original methods if no more listeners if (listeners.length === 0) { window.history.pushState = originalPushState; window.history.replaceState = originalReplaceState; } }; } function getSnapshot(): LocationState | undefined { return currentSnapshot; } function getServerSnapshot(): LocationState | undefined { return undefined; } export function useLocation() { return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); }