Created
April 8, 2026 06:39
-
-
Save khasky/c703cd32db2cd342b5c5dad49bbc23c1 to your computer and use it in GitHub Desktop.
useHashChange React Hook
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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