Skip to content

Instantly share code, notes, and snippets.

@khasky
Created April 8, 2026 06:39
Show Gist options
  • Select an option

  • Save khasky/c703cd32db2cd342b5c5dad49bbc23c1 to your computer and use it in GitHub Desktop.

Select an option

Save khasky/c703cd32db2cd342b5c5dad49bbc23c1 to your computer and use it in GitHub Desktop.
useHashChange React Hook
// Keeps React state in sync with `window.location.hash` (fragment without `#`)
// via `hashchange`, and seeds from the initial hash on mount.
import React from 'react';
export function useHashChange() {
const [activeItemId, setActiveItemId] = React.useState<string | null>(null);
React.useEffect(() => {
if (!activeItemId && window.location.hash) {
setActiveItemId(window.location.hash.substring(1));
}
const handleHashChange = () => {
if (window.location.hash) {
setActiveItemId(window.location.hash.substring(1));
} else {
setActiveItemId(null);
}
};
window.addEventListener('hashchange', handleHashChange);
return () => {
window.removeEventListener('hashchange', handleHashChange);
};
}, []);
return activeItemId;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment