Skip to content

Commit

Permalink
Memoize useRouter from next/navigation when used in Pages Router (#52177
Browse files Browse the repository at this point in the history
)

## 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
  • Loading branch information
timneutkens authored and shuding committed Jul 8, 2023
1 parent 6643d50 commit a0cc29a
Showing 1 changed file with 5 additions and 1 deletion.
6 changes: 5 additions & 1 deletion packages/next/src/client/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
<Container
fn={(error) =>
Expand All @@ -336,7 +340,7 @@ function AppContainer({
)
}
>
<AppRouterContext.Provider value={adaptForAppRouterInstance(router)}>
<AppRouterContext.Provider value={adaptedForAppRouter}>
<SearchParamsContext.Provider value={adaptForSearchParams(router)}>
<PathnameContextProviderAdapter
router={router}
Expand Down

0 comments on commit a0cc29a

Please sign in to comment.