Skip to content

Instantly share code, notes, and snippets.

@akbarjondev
Created February 21, 2023 15:40
Show Gist options
  • Save akbarjondev/0ddf2ea9aa79a82b8597e0305ada88ad to your computer and use it in GitHub Desktop.
Save akbarjondev/0ddf2ea9aa79a82b8597e0305ada88ad to your computer and use it in GitHub Desktop.
Retrieve previous route and/or route history in Next router
import { useRouter } from 'next/router';
import { useRef } from 'react';
export const usePreviousRoute = () => {
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