1import { useHistory } from 'react-router-dom'
2
3
4const [ locationKeys, setLocationKeys ] = useState([])
5const history = useHistory()
6
7useEffect(() => {
8 return history.listen(location => {
9 if (history.action === 'PUSH') {
10 setLocationKeys([ location.key ])
11 }
12
13 if (history.action === 'POP') {
14 if (locationKeys[1] === location.key) {
15 setLocationKeys(([ _, ...keys ]) => keys)
16
17 // Handle forward event
18
19 } else {
20 setLocationKeys((keys) => [ location.key, ...keys ])
21
22 // Handle back event
23
24 }
25 }
26 })
27}, [ locationKeys, ])
1const {history} = useRouter();
2 useEffect(() => {
3 return () => {
4 // && history.location.pathname === "any specific path")
5 if (history.action === "POP") {
6 history.replace(history.location.pathname, /* the new state */);
7 }
8 };
9 }, [history])
10