Skip to content

useHash

Track and update the window location hash value using this hook.

Parameters

  • the initial hash string (optional).

Return Values

It returns a tuple of 2 values:

IndexNameTypeDescription
0hashStringthe current hash value.
1setHashFunctionupdates the hash value.

Example Usage

tsx
import { useHash } from 'react-pre-hooks';

export default function Example() {
  const [hash, setHash] = useHash();

  return (
    <main>
      <p>Current hash: {hash}</p>
      <a href="#hash-one">One</a>
      <a href="#hash-two">Two</a>
      <a href="#hash-three">Three</a>
      <button onClick={() => setHash(crypto.randomUUID())}>Random hash</button>
    </main>
  );
}
import { useHash } from 'react-pre-hooks';

export default function Example() {
  const [hash, setHash] = useHash();

  return (
    <main>
      <p>Current hash: {hash}</p>
      <a href="#hash-one">One</a>
      <a href="#hash-two">Two</a>
      <a href="#hash-three">Three</a>
      <button onClick={() => setHash(crypto.randomUUID())}>Random hash</button>
    </main>
  );
}

Released under the MIT License.