Skip to content

Instantly share code, notes, and snippets.

@matthewhartman
Forked from tim-field/useRouter.js
Created March 21, 2019 07:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save matthewhartman/e62b14db3fafc22e9cd777332d0810b2 to your computer and use it in GitHub Desktop.
Save matthewhartman/e62b14db3fafc22e9cd777332d0810b2 to your computer and use it in GitHub Desktop.
Hooks Router
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