Shadcn Hooks

useHash

A hook to get current hash

useHash

npx shadcn@latest add "https://shadcn-hooks.vercel.app/r/use-hash.json"
pnpm dlx shadcn@latest add "https://shadcn-hooks.vercel.app/r/use-hash.json"
yarn dlx shadcn@latest add "https://shadcn-hooks.vercel.app/r/use-hash.json"
bun x shadcn@latest add "https://shadcn-hooks.vercel.app/r/use-hash.json"

Copy and paste the following code into your project.

use-hash.ts
import { useSyncExternalStore } from 'react'

function subscribe(onStoreChange: () => void) {
  window.addEventListener('hashchange', onStoreChange)
  return () => window.removeEventListener('hashchange', onStoreChange)
}

function getSnapshot() {
  return window.location.hash
}

function getServerSnapshot() {
  return ''
}

export function useHash() {
  return useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)
}

credits

Last updated on

On this page