Created
January 14, 2021 08:18
-
-
Save joshxyzhimself/0509c479173053f84b45d4934e919ccc to your computer and use it in GitHub Desktop.
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 { useState, useEffect, useCallback } from 'react'; | |
function useHistory () { | |
const [pathname, set_pathname] = useState(window.location.pathname); | |
const push = useCallback((next_pathname) => { | |
if (pathname !== next_pathname) { | |
window.history.pushState(null, null, next_pathname); | |
set_pathname(next_pathname); | |
} | |
}, [pathname]); | |
const replace = useCallback((next_pathname) => { | |
if (pathname !== next_pathname) { | |
window.history.replaceState(null, null, next_pathname); | |
set_pathname(next_pathname); | |
} | |
}, [pathname]); | |
useEffect(() => { | |
const popstate_listener = () => { | |
set_pathname(window.location.pathname); | |
}; | |
window.addEventListener('popstate', popstate_listener); | |
return () => { | |
window.removeEventListener('popstate', popstate_listener); | |
}; | |
}, []); | |
const history = { pathname, push, replace }; | |
return history; | |
} | |
export default useHistory; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment