mirror of
https://github.com/streamich/react-use.git
synced 2026-01-18 14:06:52 +00:00
34 lines
723 B
TypeScript
34 lines
723 B
TypeScript
import { useState, useCallback } from 'react';
|
|
import useLifecycles from './useLifecycles';
|
|
|
|
/**
|
|
* read and write url hash, response to url hash change
|
|
*/
|
|
export const useHash = () => {
|
|
const [hash, setHash] = useState(() => window.location.hash);
|
|
|
|
const onHashChange = useCallback(() => {
|
|
setHash(window.location.hash);
|
|
}, []);
|
|
|
|
useLifecycles(
|
|
() => {
|
|
window.addEventListener('hashchange', onHashChange);
|
|
},
|
|
() => {
|
|
window.removeEventListener('hashchange', onHashChange);
|
|
}
|
|
);
|
|
|
|
const _setHash = useCallback(
|
|
(newHash: string) => {
|
|
if (newHash !== hash) {
|
|
window.location.hash = newHash;
|
|
}
|
|
},
|
|
[hash]
|
|
);
|
|
|
|
return [hash, _setHash] as const;
|
|
};
|