All hooks / Storage and URL

useHash

159 B minified and brotliedSourceMarkdown✓ Works in all modern browsers

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.

Billingtab: profile · hash (none)

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]
ParameterDescription
serverValueValue 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

UsesChromeEdgeFirefoxSafariChrome AndroidSafari iOS
hashchange eventWidely available4+12+3.6+5+18+5+
Navigation APIoptionalNewly available102+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).