-
-
Save matthewhartman/e62b14db3fafc22e9cd777332d0810b2 to your computer and use it in GitHub Desktop.
Hooks Router
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect, useState } from "react" | |
import { createBrowserHistory } from "history" | |
const history = createBrowserHistory() | |
const trim = url => url.replace(/^\/|\/$/g, "") | |
function useRouter(initial = "") { | |
const [route, setRoute] = useState(initial) | |
useEffect(() => { | |
const { pathname, search } = new URL(route, window.location.href) | |
if (window.location.pathname !== pathname) { | |
history.push(pathname) | |
setRoute(trim(document.location.pathname)) | |
} else if (window.location.search !== search) { | |
history.replace(pathname + search) | |
} | |
}, [route]) | |
useEffect(() => { | |
window.onpopstate = function historyChange(ev) { | |
if (ev.type === "popstate") { | |
setRoute(trim(document.location.pathname)) | |
} | |
} | |
setRoute(trim(document.location.pathname)) | |
}, []) | |
return [route, setRoute] | |
} | |
export default useRouter |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment