I am currently using tis to listen to changes to url hash but it is not detecting changes even tho the url is changing.
import { useCallback, useEffect, useLayoutEffect, useState } from "react";
type UseHashReturn = [string, (newHash: string) => void];
const useIsomorphicLayoutEffect =
typeof window !== "undefined" ? useLayoutEffect : useEffect;
/**
- Hook to read and write the hash of the current url. It also updates the hash when the url changes.
- @returns {UseHashReturn} An array of two elements:
-
- The current hash of the url.
-
- A function to set the hash of the url.
*/
export function useHash(): UseHashReturn {
const [hash, setHash] = useState(() =>
typeof window !== "undefined" ? window.location.hash : "",
);
- A function to set the hash of the url.
const onHashChange = useCallback(() => {
setHash(window.location.hash);
}, []);
useIsomorphicLayoutEffect(() => {
window.addEventListener("hashchange", onHashChange);
return () => {
window.removeEventListener("hashchange", onHashChange);
};
}, []);
const _setHash = useCallback(
(newHash: string) => {
if (newHash !== hash) {
window.location.hash = newHash;
}
},
[hash],
);
return [hash, _setHash] as const;
}