-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
use-hash.ts
33 lines (27 loc) · 875 Bytes
/
use-hash.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import { useState, useEffect } from 'react';
import { useWindowEvent } from '../use-window-event/use-window-event';
interface UseHashOptions {
getInitialValueInEffect?: boolean;
}
export function useHash({ getInitialValueInEffect = false }: UseHashOptions = {}) {
const [hash, setHashValue] = useState<string>(
getInitialValueInEffect ? window.location.hash || '' : ''
);
const setHash = (value: string) => {
const valueWithHash = value.startsWith('#') ? value : `#${value}`;
window.location.hash = valueWithHash;
setHashValue(valueWithHash);
};
useWindowEvent('hashchange', () => {
const newHash = window.location.hash;
if (hash !== newHash) {
setHashValue(hash);
}
});
useEffect(() => {
if (getInitialValueInEffect) {
setHashValue(window.location.hash);
}
}, []);
return [hash, setHash] as const;
}