import { useEffect, useState } from "react";

/** Re-renders when `location.search` changes (popstate or custom `locationchange`). */
export function useLocationSearch(): string {
  const [search, setSearch] = useState(() => window.location.search);

  useEffect(() => {
    const sync = () => setSearch(window.location.search);
    window.addEventListener("popstate", sync);
    window.addEventListener("locationchange", sync);
    return () => {
      window.removeEventListener("popstate", sync);
      window.removeEventListener("locationchange", sync);
    };
  }, []);

  return search;
}
