Unverified Commit 7ba4a0d5 authored by Florian Lopez Plaza's avatar Florian Lopez Plaza Committed by GitHub

FIX [#58788]: Fixed useParams hook undesired re-renders and updated it to use…

FIX [#58788]: Fixed useParams hook undesired re-renders and updated it to use PathParamsContext in the app router. (#60708)

Moved app-dir path params parsing logic from `useParams` to `AppRouter`.
This allows for the use of `PathParamsContext` in the `useParams` hook
for both pages and app routers. In addition, this allows for memoization
of the layout tree which fixes undesired re-renders of the `useParams`
hook.

Fixes [#58788](https://github.com/vercel/next.js/issues/58788)
Closes NEXT-2434

---------
Co-authored-by: 's avatarZack Tanner <zacktanner@gmail.com>
parent c48a0f8e
...@@ -46,6 +46,7 @@ import { createHrefFromUrl } from './router-reducer/create-href-from-url' ...@@ -46,6 +46,7 @@ import { createHrefFromUrl } from './router-reducer/create-href-from-url'
import { import {
SearchParamsContext, SearchParamsContext,
PathnameContext, PathnameContext,
PathParamsContext,
} from '../../shared/lib/hooks-client-context.shared-runtime' } from '../../shared/lib/hooks-client-context.shared-runtime'
import { import {
useReducerWithReduxDevtools, useReducerWithReduxDevtools,
...@@ -64,6 +65,8 @@ import { createInfinitePromise } from './infinite-promise' ...@@ -64,6 +65,8 @@ import { createInfinitePromise } from './infinite-promise'
import { NEXT_RSC_UNION_QUERY } from './app-router-headers' import { NEXT_RSC_UNION_QUERY } from './app-router-headers'
import { removeBasePath } from '../remove-base-path' import { removeBasePath } from '../remove-base-path'
import { hasBasePath } from '../has-base-path' import { hasBasePath } from '../has-base-path'
import { PAGE_SEGMENT_KEY } from '../../shared/lib/segment'
import type { Params } from '../../shared/lib/router/utils/route-matcher'
const isServer = typeof window === 'undefined' const isServer = typeof window === 'undefined'
// Ensure the initialParallelRoutes are not combined because of double-rendering in the browser with Strict Mode. // Ensure the initialParallelRoutes are not combined because of double-rendering in the browser with Strict Mode.
...@@ -98,6 +101,36 @@ export function urlToUrlWithoutFlightMarker(url: string): URL { ...@@ -98,6 +101,36 @@ export function urlToUrlWithoutFlightMarker(url: string): URL {
return urlWithoutFlightParameters return urlWithoutFlightParameters
} }
// this function performs a depth-first search of the tree to find the selected
// params
function getSelectedParams(
currentTree: FlightRouterState,
params: Params = {}
): Params {
const parallelRoutes = currentTree[1]
for (const parallelRoute of Object.values(parallelRoutes)) {
const segment = parallelRoute[0]
const isDynamicParameter = Array.isArray(segment)
const segmentValue = isDynamicParameter ? segment[1] : segment
if (!segmentValue || segmentValue.startsWith(PAGE_SEGMENT_KEY)) continue
// Ensure catchAll and optional catchall are turned into an array
const isCatchAll =
isDynamicParameter && (segment[2] === 'c' || segment[2] === 'oc')
if (isCatchAll) {
params[segment[0]] = segment[1].split('/')
} else if (isDynamicParameter) {
params[segment[0]] = segment[1]
}
params = getSelectedParams(parallelRoute, params)
}
return params
}
type AppRouterProps = Omit< type AppRouterProps = Omit<
Omit<InitialRouterStateParameters, 'isServer' | 'location'>, Omit<InitialRouterStateParameters, 'isServer' | 'location'>,
'initialParallelRoutes' 'initialParallelRoutes'
...@@ -585,6 +618,11 @@ function Router({ ...@@ -585,6 +618,11 @@ function Router({
return findHeadInCache(cache, tree[1]) return findHeadInCache(cache, tree[1])
}, [cache, tree]) }, [cache, tree])
// Add memoized pathParams for useParams.
const pathParams = useMemo(() => {
return getSelectedParams(tree)
}, [tree])
let head let head
if (matchingHead !== null) { if (matchingHead !== null) {
// The head is wrapped in an extra component so we can use // The head is wrapped in an extra component so we can use
...@@ -631,33 +669,35 @@ function Router({ ...@@ -631,33 +669,35 @@ function Router({
appRouterState={useUnwrapState(reducerState)} appRouterState={useUnwrapState(reducerState)}
sync={sync} sync={sync}
/> />
<PathnameContext.Provider value={pathname}> <PathParamsContext.Provider value={pathParams}>
<SearchParamsContext.Provider value={searchParams}> <PathnameContext.Provider value={pathname}>
<GlobalLayoutRouterContext.Provider <SearchParamsContext.Provider value={searchParams}>
value={{ <GlobalLayoutRouterContext.Provider
buildId, value={{
changeByServerResponse, buildId,
tree, changeByServerResponse,
focusAndScrollRef, tree,
nextUrl, focusAndScrollRef,
}} nextUrl,
> }}
<AppRouterContext.Provider value={appRouter}> >
<LayoutRouterContext.Provider <AppRouterContext.Provider value={appRouter}>
value={{ <LayoutRouterContext.Provider
childNodes: cache.parallelRoutes, value={{
tree, childNodes: cache.parallelRoutes,
// Root node always has `url` tree,
// Provided in AppTreeContext to ensure it can be overwritten in layout-router // Root node always has `url`
url: canonicalUrl, // Provided in AppTreeContext to ensure it can be overwritten in layout-router
}} url: canonicalUrl,
> }}
{content} >
</LayoutRouterContext.Provider> {content}
</AppRouterContext.Provider> </LayoutRouterContext.Provider>
</GlobalLayoutRouterContext.Provider> </AppRouterContext.Provider>
</SearchParamsContext.Provider> </GlobalLayoutRouterContext.Provider>
</PathnameContext.Provider> </SearchParamsContext.Provider>
</PathnameContext.Provider>
</PathParamsContext.Provider>
</> </>
) )
} }
......
...@@ -2,7 +2,6 @@ import { useContext, useMemo } from 'react' ...@@ -2,7 +2,6 @@ import { useContext, useMemo } from 'react'
import type { FlightRouterState } from '../../server/app-render/types' import type { FlightRouterState } from '../../server/app-render/types'
import { import {
AppRouterContext, AppRouterContext,
GlobalLayoutRouterContext,
LayoutRouterContext, LayoutRouterContext,
type AppRouterInstance, type AppRouterInstance,
} from '../../shared/lib/app-router-context.shared-runtime' } from '../../shared/lib/app-router-context.shared-runtime'
...@@ -152,36 +151,6 @@ interface Params { ...@@ -152,36 +151,6 @@ interface Params {
[key: string]: string | string[] [key: string]: string | string[]
} }
// this function performs a depth-first search of the tree to find the selected
// params
function getSelectedParams(
tree: FlightRouterState,
params: Params = {}
): Params {
const parallelRoutes = tree[1]
for (const parallelRoute of Object.values(parallelRoutes)) {
const segment = parallelRoute[0]
const isDynamicParameter = Array.isArray(segment)
const segmentValue = isDynamicParameter ? segment[1] : segment
if (!segmentValue || segmentValue.startsWith(PAGE_SEGMENT_KEY)) continue
// Ensure catchAll and optional catchall are turned into an array
const isCatchAll =
isDynamicParameter && (segment[2] === 'c' || segment[2] === 'oc')
if (isCatchAll) {
params[segment[0]] = segment[1].split('/')
} else if (isDynamicParameter) {
params[segment[0]] = segment[1]
}
params = getSelectedParams(parallelRoute, params)
}
return params
}
/** /**
* A [Client Component](https://nextjs.org/docs/app/building-your-application/rendering/client-components) hook * A [Client Component](https://nextjs.org/docs/app/building-your-application/rendering/client-components) hook
* that lets you read a route's dynamic params filled in by the current URL. * that lets you read a route's dynamic params filled in by the current URL.
...@@ -201,18 +170,8 @@ function getSelectedParams( ...@@ -201,18 +170,8 @@ function getSelectedParams(
*/ */
export function useParams<T extends Params = Params>(): T { export function useParams<T extends Params = Params>(): T {
clientHookInServerComponentError('useParams') clientHookInServerComponentError('useParams')
const globalLayoutRouter = useContext(GlobalLayoutRouterContext)
const pathParams = useContext(PathParamsContext)
return useMemo(() => {
// When it's under app router
if (globalLayoutRouter?.tree) {
return getSelectedParams(globalLayoutRouter.tree) as T
}
// When it's under client side pages router return useContext(PathParamsContext) as T
return pathParams as T
}, [globalLayoutRouter?.tree, pathParams])
} }
/** Get the canonical parameters from the current level to the leaf node. */ /** Get the canonical parameters from the current level to the leaf node. */
......
'use client'
import Link from 'next/link'
import { useParams } from 'next/navigation'
export default function Page() {
const params = useParams()
return (
<div>
<Link href="/foo">Link</Link>
<div id="random">{Math.random()}</div>
<div id="params">{JSON.stringify(params?.dynamic)}</div>
</div>
)
}
import { useParams } from 'next/navigation'
export default function Page() {
const params = useParams()
return (
<div>
<div id="params">{JSON.stringify(params?.dynamic)}</div>
</div>
)
}
...@@ -41,5 +41,19 @@ createNextDescribe( ...@@ -41,5 +41,19 @@ createNextDescribe(
expect(await browser.elementByCss('#param-id').text()).toBe('a') expect(await browser.elementByCss('#param-id').text()).toBe('a')
expect(await browser.elementByCss('#param-id2').text()).toBe('b') expect(await browser.elementByCss('#param-id2').text()).toBe('b')
}) })
it('should work on pages router', async () => {
const browser = await next.browser('/pages-dir/foobar')
expect(await browser.elementById('params').text()).toBe('"foobar"')
})
it("shouldn't rerender host component when prefetching", async () => {
const browser = await next.browser('/rerenders/foobar')
const initialRandom = await browser.elementById('random').text()
const link = await browser.elementByCss('a')
await link.hover()
const newRandom = await browser.elementById('random').text()
expect(initialRandom).toBe(newRandom)
})
} }
) )
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