useRouter
Usage
import { useState, useEffect } from 'react';
interface RouterObject {
pathname: string;
search: string;
hash: string;
state: any;
}
const useRouter = (): RouterObject => {
const [location, setLocation] = useState<RouterObject>({
pathname: window.location.pathname,
search: window.location.search,
hash: window.location.hash,
state: null,
});
useEffect(() => {
const handleLocationChange = () => {
setLocation({
pathname: window.location.pathname,
search: window.location.search,
hash: window.location.hash,
state: history.state,
});
};
window.addEventListener('popstate', handleLocationChange);
return () => window.removeEventListener('popstate', handleLocationChange);
}, []);
return location;
};
export default useRouter;Last updated