use-hash

Get and set hash value in the URL

Import

Usage

use-hash returns hash from URL, subscribes to its changes with hashchange event and allows changing it with setHash function:

Current hash:

import { useHash, randomId } from '@mantine/hooks';
import { Button, Text, Code } from '@mantine/core';

function Demo() {
  const [hash, setHash] = useHash();
  return (
    <>
      <Button onClick={() => setHash(randomId())}>Set hash to random string</Button>
      <Text>Current hash: <Code>{hash}</Code></Text>
    </>
  );
}

Initial state value

By default, use-hash will retrieve value in useEffect. If you want to get initial value as soon as hook is called, set getInitialValueInEffect to false. Note that this option is not compatible with server side rendering – you can only use it if your app is client-side only.

import { Button } from '@mantine/core';
import { useHash } from '@mantine/hooks';

function Demo() {
  const [hash, setHash] = useHash({ getInitialValueInEffect: false });
  return (
    <Button onClick={() => setHash('new-hash')}>Change hash</Button>
  );
}

Definition

function useHash(options: {
  getInitialValueInEffect?: boolean;
}): readonly [string, (value: string) => void];