Problem
I'm assuming you want to add and remove history (similar to a real browser history) instead of just constantly replacing the history with whatever route was previous. Instead of constantly replacing the pathname upon a route change, you'll want to conditionally add/remove it from some sort of history.
Solution
Here's a hook that utilizes an Array (basically a flat array of asPath
strings -- you may want to limit the size of the Array to prevent performance issues):
import * as React from "react";
import { useRouter } from "next/router";
const usePreviousRoute = () => {
const { asPath } = useRouter();
// initialize history with current URL path
const [history, setHistory] = React.useState([asPath]);
const lastHistoryIndex = history.length - 2;
// get second to last route in history array
const previousRoute = history[lastHistoryIndex > 0 ? lastHistoryIndex : 0];
const removeHistory = () => {
// get current history
setHistory((prevHistory) =>
// check if the history has more than 1 item
prevHistory.length > 1
// if it does, remove the last history item
? prevHistory.filter((_, index) => index !== prevHistory.length - 1)
// else don't remove any history
: prevHistory
);
};
React.useEffect(() => {
// get current history
setHistory((prevHistory) =>
// check if the last history item is the current path
prevHistory[prevHistory.length - 1] !== asPath
// if not, add current path to history
? [...prevHistory, asPath]
// else don't add any history
: prevHistory
);
}, [asPath]);
return { previousRoute, removeHistory };
};
export default usePreviousRoute;
With capped history:
React.useEffect(() => {
// get current history
setHistory((prevHistory) =>
// check if last history item is current path
prevHistory[prevHistory.length - 1] !== asPath
// if not...
? [
// check if history has more than 10 items
// spread result into shallow copied array
...(prevHistory.length > 9
// if it does have more than 10 items, remove first item
? prevHistory.filter((_, index) => index !== 0)
// else don't remove history
: prevHistory),
asPath
]
// else don't remove history
: prevHistory
);
}, [asPath]);
Demo
Source Code:

Browser Demo URL: https://knfoj.sse.codesandbox.io/
Demo Code
Navigation.js
/* eslint-disable jsx-a11y/anchor-is-valid */
import * as React from "react";
import Link from "next/link";
import { useHistoryContext } from "../../hooks/useRouteHistory";
import GoBackLink from "../GoBackLink";
import styles from "./Navigation.module.css";
const Navigation = () => {
const { history } = useHistoryContext();
return (
<>
<nav className={styles.navbar}>
{[
{ title: "Home", url: "/" },
{ title: "About", url: "/about" },
{ title: "Example", url: "/example" },
{ title: "NoLayout", url: "/nolayout" }
].map(({ title, url }) => (
<Link key={title} href={url} passHref>
<a className={styles.link}>{title}</a>
</Link>
))}
</nav>
<GoBackLink />
<div className={styles.history}>
<h4 style={{ marginBottom: 0 }}>History</h4>
<pre className={styles.code}>
<code>{JSON.stringify(history, null, 2)}</code>
</pre>
</div>
</>
);
};
export default Navigation;
useRouteHistory.js
import * as React from "react";
import { useRouter } from "next/router";
export const HistoryContext = React.createContext();
export const useHistoryContext = () => React.useContext(HistoryContext);
export const usePreviousRoute = () => {
const { asPath } = useRouter();
const [history, setHistory] = React.useState([asPath]);
const lastHistoryIndex = history.length - 2;
const previousRoute = history[lastHistoryIndex > 0 ? lastHistoryIndex : 0];
const removeHistory = () => {
setHistory((prevHistory) =>
prevHistory.length > 1
? prevHistory.filter((_, index) => index !== prevHistory.length - 1)
: prevHistory
);
};
React.useEffect(() => {
setHistory((prevHistory) =>
prevHistory[prevHistory.length - 1] !== asPath
? [...prevHistory, asPath]
: prevHistory
);
}, [asPath]);
return { history, previousRoute, removeHistory };
};
export const HistoryProvider = ({ children }) => {
const historyProps = usePreviousRoute();
return (
<HistoryContext.Provider
value={{
...historyProps
}}
>
{children}
</HistoryContext.Provider>
);
};
export default HistoryProvider;
_app.js
import * as React from "react";
import HistoryContext from "../hooks/useRouteHistory";
const App = ({ Component, pageProps }) => (
<HistoryContext>
<Component {...pageProps} />
</HistoryContext>
);
export default App;
index.js
import Layout from "../components/Layout";
const IndexPage = () => (
<Layout>
<h1>Index Page</h1>
<p>
...
</p>
</Layout>
);
export default IndexPage;