Unverified Commit ae3db7ce authored by Tim Neutkens's avatar Tim Neutkens Committed by GitHub

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
parent 4f75c799
...@@ -326,6 +326,10 @@ function renderApp(App: AppComponent, appProps: AppProps) { ...@@ -326,6 +326,10 @@ function renderApp(App: AppComponent, appProps: AppProps) {
function AppContainer({ function AppContainer({
children, children,
}: React.PropsWithChildren<{}>): React.ReactElement { }: React.PropsWithChildren<{}>): React.ReactElement {
// Create a memoized value for next/navigation router context.
const adaptedForAppRouter = React.useMemo(() => {
return adaptForAppRouterInstance(router)
}, [])
return ( return (
<Container <Container
fn={(error) => fn={(error) =>
...@@ -336,7 +340,7 @@ function AppContainer({ ...@@ -336,7 +340,7 @@ function AppContainer({
) )
} }
> >
<AppRouterContext.Provider value={adaptForAppRouterInstance(router)}> <AppRouterContext.Provider value={adaptedForAppRouter}>
<SearchParamsContext.Provider value={adaptForSearchParams(router)}> <SearchParamsContext.Provider value={adaptForSearchParams(router)}>
<PathnameContextProviderAdapter <PathnameContextProviderAdapter
router={router} router={router}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment