ovreride browser back button in react js code example
Example: if back react
import { useHistory } from 'react-router-dom'
const [ locationKeys, setLocationKeys ] = useState([])
const history = useHistory()
useEffect(() => {
return history.listen(location => {
if (history.action === 'PUSH') {
setLocationKeys([ location.key ])
}
if (history.action === 'POP') {
if (locationKeys[1] === location.key) {
setLocationKeys(([ _, ...keys ]) => keys)
} else {
setLocationKeys((keys) => [ location.key, ...keys ])
}
}
})
}, [ locationKeys, ])