Skip to content

Instantly share code, notes, and snippets.

@mrhether
Created January 28, 2022 19:44
Show Gist options
  • Save mrhether/83e85b7880f4ad17196f08861eb8dbdd to your computer and use it in GitHub Desktop.
Save mrhether/83e85b7880f4ad17196f08861eb8dbdd to your computer and use it in GitHub Desktop.
import { Location } from 'history';
import { useEffect, useState } from 'react';
import { useHistory } from 'react-router';
const useBrowserBackStack = () => {
const history = useHistory();
const [backStack, setBackStack] = useState<Location[]>([]);
useEffect(() => {
history.listen((location, action) => {
setBackStack(backStack => {
switch (action) {
case 'POP':
return backStack.slice(0, backStack.length - 1);
case 'PUSH':
return [...backStack, location];
case 'REPLACE':
return [...backStack.slice(0, backStack.length - 1), location];
}
});
});
}, [setBackStack, history]);
return backStack;
};
export default useBrowserBackStack;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment