Skip to content

Instantly share code, notes, and snippets.

@camflan
Created November 2, 2021 19:27
Show Gist options
  • Save camflan/682bc321db1e6f169fd74feb12ca6534 to your computer and use it in GitHub Desktop.
Save camflan/682bc321db1e6f169fd74feb12ca6534 to your computer and use it in GitHub Desktop.
Stable nextjs router navigation methods
import { useRouter } from "next/router";
import type { NextRouter } from "next/router";
import { useRef, useState } from "react";
type RouterNavigationMethods = Pick<NextRouter, "back" | "push" | "reload" | "replace">;
/**
* useRouter doesn't return stable navigation methods, this gives us something
* stable to call, even as the router changes behind the scenes.
*
* Note, this uses state instead of memo in case the React implementation ends
* up evicting memoized objects in the future
* Inspired by: https://github.com/vercel/next.js/issues/18127#issuecomment-950907739
*/
export default function useRouterNavigation(): RouterNavigationMethods {
const router = useRouter();
const routerRef = useRef(router);
routerRef.current = router;
const [routerNavigation] = useState<RouterNavigationMethods>({
back: routerRef.current.back,
push: routerRef.current.push,
reload: routerRef.current.reload,
replace: routerRef.current.replace,
});
return routerNavigation;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment