From a0cc29a539fef7de0e127f7bdcc43e16b5e9f8d4 Mon Sep 17 00:00:00 2001 From: Tim Neutkens Date: Tue, 4 Jul 2023 11:11:21 +0200 Subject: [PATCH] Memoize useRouter from next/navigation when used in Pages Router (#52177) ## What? Ensures the router instance passed for `next/navigation` in Pages Router is a stable reference. For App Router the router instance is already a stable reference, so making this one stable too would fix #18127. ## How? Added `React.useMemo` around `adaptForAppRouterInstance`, previously it was recreated each render but that's not needed for this particular case. The searchParamsContext and pathnameContext do need a new value each render in order to ensure they get the latest value. Fixes #18127 Fixes NEXT-1375 --- packages/next/src/client/index.tsx | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/packages/next/src/client/index.tsx b/packages/next/src/client/index.tsx index 87a45c7ab4ed1..d1b1140616976 100644 --- a/packages/next/src/client/index.tsx +++ b/packages/next/src/client/index.tsx @@ -326,6 +326,10 @@ function renderApp(App: AppComponent, appProps: AppProps) { function AppContainer({ children, }: React.PropsWithChildren<{}>): React.ReactElement { + // Create a memoized value for next/navigation router context. + const adaptedForAppRouter = React.useMemo(() => { + return adaptForAppRouterInstance(router) + }, []) return ( @@ -336,7 +340,7 @@ function AppContainer({ ) } > - +