Skip to content

Instantly share code, notes, and snippets.

@isocroft
Created February 26, 2024 20:27
Show Gist options
  • Save isocroft/b45ec84dbee6966b0e8ec8f218daeb9e to your computer and use it in GitHub Desktop.
Save isocroft/b45ec84dbee6966b0e8ec8f218daeb9e to your computer and use it in GitHub Desktop.
A custom NextJS hook that returns the previous route visited in a browser application
import { useRouter } from "next/router";
import { useRef } from "react";
export const useNexJSPreviousRoute = () => {
const router = useRouter();
const ref = useRef<string | null>(null);
router.events?.on("routeChangeStart", () => {
ref.current = router.asPath;
});
return ref.current;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment