@jk-core/hooks
Version:
hooks for jk
44 lines (36 loc) • 1.14 kB
text/typescript
import { useEffect } from 'react';
interface Update {
action: 'POP' | 'PUSH' | 'REPLACE';
location: Location;
}
interface Listener {
(update: Update): void;
}
const useHistoryEvent = (listener: Listener) => {
useEffect(() => {
const handlePopState = () => {
const action = 'POP';
const { location } = window;
listener({ action, location });
};
const handlePushState = () => {
const action = 'PUSH';
const { location } = window;
listener({ action, location });
};
const handleReplaceState = () => {
const action = 'REPLACE';
const { location } = window;
listener({ action, location });
};
window.addEventListener('popstate', handlePopState);
window.addEventListener('pushstate', handlePushState);
window.addEventListener('replacestate', handleReplaceState);
return () => {
window.removeEventListener('popstate', handlePopState);
window.removeEventListener('pushstate', handlePushState);
window.removeEventListener('replacestate', handleReplaceState);
};
}, [listener]);
};
export default useHistoryEvent;