#How to get previous url from current pathname
1 messages · Page 1 of 1 (latest)
To get the previous URL from the current pathname in Next.js, you can use a custom hook that utilizes the usePathname hook from Next.js and the useEffect and useRef hooks from React. Here's an example of how you can do this:
import { useEffect, useRef } from "react";
import { usePathname } from 'next/navigation'
export const usePrevious = <T>(value: T) => {
const ref = useRef<T>(value);
useEffect(() => {
ref.current = value;
});
return ref.current;
};
export default function ExampleComponent() {
const pathname = usePathname();
const prevPathname = usePrevious(pathname);
useEffect(() => {
if (prevPathname !== pathname) {
console.log('Previous pathname:', prevPathname);
}
}, [pathname, prevPathname]);
// rest of your component
}
In this example, usePrevious is a custom hook that keeps track of the previous value of its argument. In ExampleComponent, we use this hook to keep track of the previous pathname. Whenever the pathname changes, we log the previous pathname.
Please note that this will give you the previous pathname, not the full URL. If you need the full URL, you can construct it using window.location.origin and the previous pathname.
Sources:
- Github Issue (closed): Docs: Problem with yandex metrics and app router. Need example or documentation > Comments Part 3 (https://github.com/vercel/next.js/issues/56882)
- Next.js > Docs > App > Api-reference > Functions > usePathname (https://nextjs.org/docs/app/api-reference/functions/use-pathname)