Skip to content

Instantly share code, notes, and snippets.

@joshxyzhimself
Created January 14, 2021 08:18
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 joshxyzhimself/0509c479173053f84b45d4934e919ccc to your computer and use it in GitHub Desktop.
Save joshxyzhimself/0509c479173053f84b45d4934e919ccc to your computer and use it in GitHub Desktop.
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