Skip to content

Instantly share code, notes, and snippets.

@Wigny
Created July 31, 2025 21:34
Show Gist options
  • Select an option

  • Save Wigny/7a6267228e7b8582db07e1e780cb67c2 to your computer and use it in GitHub Desktop.

Select an option

Save Wigny/7a6267228e7b8582db07e1e780cb67c2 to your computer and use it in GitHub Desktop.
import { useSyncExternalStore } from 'react';
function onHashChange(callback: () => void) {
window.addEventListener('hashchange', callback);
return () => window.removeEventListener('hashchange', callback);
}
function getHash() {
return window.location.hash.slice(1) || null;
}
function setHash(hash: string | null) {
window.location.hash = hash ?? '';
}
export const useURLHash = (): [string | null, (hash: string | null) => void] => {
const hash = useSyncExternalStore(onHashChange, getHash);
return [hash, setHash];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment