Created
January 28, 2022 19:44
-
-
Save mrhether/83e85b7880f4ad17196f08861eb8dbdd to your computer and use it in GitHub Desktop.
This file contains 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 { 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