All hooks / Storage and URL
useHash
The URL hash, like location.hash ('#pricing', or '' when there is none), and a setter. Re-renders on hash links, back/forward, setHash, and router navigation that uses history.pushState (e.g. Next.js <Link href="#pricing">, in browsers with the Navigation API).
The server never sees the hash, so the server render and hydration use serverValue, then the real hash with no hydration mismatch.
Import
import { useHash } from '@vincent.ri/react-tils'
// or only this hook
import { useHash } from '@vincent.ri/react-tils/useHash'Usage
const [hash, setHash] = useHash()
const tab = hash === '#billing' ? 'billing' : 'profile'
return <button onClick={() => setHash('#billing')}>Billing</button>Live demo
Pick a tab, then reload or press Back.
When to use it
Tabs or an open panel that should survive reload and be linkable (/settings#billing), or highlighting the section a link pointed to.
When not to
The state must reach the server or appear in search results; use a query param (useSearchParam, or your router's). To style the target element, use CSS :target.
API
function useHash(serverValue?: string): [string, (hash: string) => void]| Parameter | Description |
|---|---|
serverValue | Value on the server and during hydration. Default ''. |
Returns [hash, setHash]. setHash('#billing') (or 'billing') adds a history entry and scrolls to a matching id, like clicking a hash link.
Browser support
| Uses | Chrome | Edge | Firefox | Safari | Chrome Android | Safari iOS |
|---|---|---|---|---|---|---|
| hashchange eventWidely available | 4+ | 12+ | 3.6+ | 5+ | 18+ | 5+ |
| Navigation APIoptionalNewly available | 102+ | 102+ | 147+ | 26.2+ | 102+ | 26.2+ |
- Router navigation that changes the URL with
history.pushState(e.g. Next.js<Link>) is noticed only where the Navigation API exists. Elsewhere the hash still updates on links, Back and Forward, and the hook's own setter.
Optional features are used when present; without them the hook still works.
First version with support, from MDN's compatibility data (web-features 3.42.0, @mdn/browser-compat-data 8.1.5).