Sometimes, we want to intercept and handle browser’s back button in React Router v6.
In this article, we’ll look at how to intercept and handle browser’s back button in React Router v6.
How to intercept and handle browser’s back button in React Router?
To intercept and handle browser’s back button in React Router, we can listen for changes in the history
object with the navigation.listen
method.
For instance, we write
import { BrowserHistory } from "history";
import React, { useContext } from "react";
import { UNSAFE_NavigationContext } from "react-router-dom";
export default function usePathname() {
const [state, setState] = React.useState(window.location.pathname);
const navigation = useContext(UNSAFE_NavigationContext)
.navigator;
React.useLayoutEffect(() => {
if (navigation) {
navigation.listen((locationListener) =>
setState(locationListener.location.pathname)
);
}
}, [navigation]);
return state;
}
to create the usePathname
hook to listen for for navigation with navigation.listen
.
We call it with a callback to listen for navigation.
In it, we call setState
with locationListener.location.pathname
to save the latest URL we navigated to as the value of state
.
Conclusion
To intercept and handle browser’s back button in React Router, we can listen for changes in the history
object with the navigation.listen
method.