Skip to content

Commit a0cc29a

Browse files
timneutkensshuding
authored andcommitted
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
1 parent 6643d50 commit a0cc29a

File tree

1 file changed

+5
-1
lines changed

1 file changed

+5
-1
lines changed

packages/next/src/client/index.tsx

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -326,6 +326,10 @@ function renderApp(App: AppComponent, appProps: AppProps) {
326326
function AppContainer({
327327
children,
328328
}: React.PropsWithChildren<{}>): React.ReactElement {
329+
// Create a memoized value for next/navigation router context.
330+
const adaptedForAppRouter = React.useMemo(() => {
331+
return adaptForAppRouterInstance(router)
332+
}, [])
329333
return (
330334
<Container
331335
fn={(error) =>
@@ -336,7 +340,7 @@ function AppContainer({
336340
)
337341
}
338342
>
339-
<AppRouterContext.Provider value={adaptForAppRouterInstance(router)}>
343+
<AppRouterContext.Provider value={adaptedForAppRouter}>
340344
<SearchParamsContext.Provider value={adaptForSearchParams(router)}>
341345
<PathnameContextProviderAdapter
342346
router={router}

0 commit comments

Comments
 (0)