# 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

```ts
import { useHash } from '@vincent.ri/react-tils'
// or only this hook
import { useHash } from '@vincent.ri/react-tils/useHash'
```

## Usage

```ts
const [hash, setHash] = useHash()
const tab = hash === '#billing' ? 'billing' : 'profile'
return <button onClick={() => setHash('#billing')}>Billing</button>
```

## 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

```ts
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

Works in all modern browsers.

- 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.

---

159 B minified and brotlied
Source: https://github.com/vincentri/react-tils/blob/main/src/useHash.ts
Docs page: https://vincentri.github.io/react-tils/hooks/useHash/
Previous: [useCookie](https://vincentri.github.io/react-tils/hooks/useCookie.md)
Next: [useSearchParam](https://vincentri.github.io/react-tils/hooks/useSearchParam.md)
