Unverified Commit 1f55ba35 authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

Change `usePathname` to return `string | null` (#42380)

This changes the API of `usePathname` to return `string | null` to
support hybrid use-cases where the pathname is unknown at build time
(during automatic static optimization and when fallback is set true with
dynamic parameters in the pathname).

This supports a cleaner DX experience for those moving from `pages/` to
`app/` so they can begin to use `usePathname` in components that are
shared across them.
parent e74de1a4
...@@ -76,7 +76,6 @@ export function useSearchParams() { ...@@ -76,7 +76,6 @@ export function useSearchParams() {
throw new Error('invariant expected search params to be mounted') throw new Error('invariant expected search params to be mounted')
} }
// eslint-disable-next-line react-hooks/rules-of-hooks
const readonlySearchParams = useMemo(() => { const readonlySearchParams = useMemo(() => {
return new ReadonlyURLSearchParams(searchParams) return new ReadonlyURLSearchParams(searchParams)
}, [searchParams]) }, [searchParams])
...@@ -87,14 +86,9 @@ export function useSearchParams() { ...@@ -87,14 +86,9 @@ export function useSearchParams() {
/** /**
* Get the current pathname. For example usePathname() on /dashboard?foo=bar would return "/dashboard" * Get the current pathname. For example usePathname() on /dashboard?foo=bar would return "/dashboard"
*/ */
export function usePathname(): string { export function usePathname(): string | null {
staticGenerationBailout('usePathname') staticGenerationBailout('usePathname')
const pathname = useContext(PathnameContext) return useContext(PathnameContext)
if (pathname === null) {
throw new Error('invariant expected pathname to be mounted')
}
return pathname
} }
// TODO-APP: getting all params when client-side navigating is non-trivial as it does not have route matchers so this might have to be a server context instead. // TODO-APP: getting all params when client-side navigating is non-trivial as it does not have route matchers so this might have to be a server context instead.
......
...@@ -39,13 +39,10 @@ import { hasBasePath } from './has-base-path' ...@@ -39,13 +39,10 @@ import { hasBasePath } from './has-base-path'
import { AppRouterContext } from '../shared/lib/app-router-context' import { AppRouterContext } from '../shared/lib/app-router-context'
import { import {
adaptForAppRouterInstance, adaptForAppRouterInstance,
adaptForPathname,
adaptForSearchParams, adaptForSearchParams,
PathnameContextProviderAdapter,
} from '../shared/lib/router/adapters' } from '../shared/lib/router/adapters'
import { import { SearchParamsContext } from '../shared/lib/hooks-client-context'
PathnameContext,
SearchParamsContext,
} from '../shared/lib/hooks-client-context'
/// <reference types="react-dom/experimental" /> /// <reference types="react-dom/experimental" />
...@@ -316,7 +313,10 @@ function AppContainer({ ...@@ -316,7 +313,10 @@ function AppContainer({
> >
<AppRouterContext.Provider value={adaptForAppRouterInstance(router)}> <AppRouterContext.Provider value={adaptForAppRouterInstance(router)}>
<SearchParamsContext.Provider value={adaptForSearchParams(router)}> <SearchParamsContext.Provider value={adaptForSearchParams(router)}>
<PathnameContext.Provider value={adaptForPathname(asPath)}> <PathnameContextProviderAdapter
router={router}
isAutoExport={self.__NEXT_DATA__.autoExport ?? false}
>
<RouterContext.Provider value={makePublicRouterInstance(router)}> <RouterContext.Provider value={makePublicRouterInstance(router)}>
<HeadManagerContext.Provider value={headManager}> <HeadManagerContext.Provider value={headManager}>
<ImageConfigContext.Provider <ImageConfigContext.Provider
...@@ -328,7 +328,7 @@ function AppContainer({ ...@@ -328,7 +328,7 @@ function AppContainer({
</ImageConfigContext.Provider> </ImageConfigContext.Provider>
</HeadManagerContext.Provider> </HeadManagerContext.Provider>
</RouterContext.Provider> </RouterContext.Provider>
</PathnameContext.Provider> </PathnameContextProviderAdapter>
</SearchParamsContext.Provider> </SearchParamsContext.Provider>
</AppRouterContext.Provider> </AppRouterContext.Provider>
</Container> </Container>
......
...@@ -84,14 +84,11 @@ import stripAnsi from 'next/dist/compiled/strip-ansi' ...@@ -84,14 +84,11 @@ import stripAnsi from 'next/dist/compiled/strip-ansi'
import { stripInternalQueries } from './internal-utils' import { stripInternalQueries } from './internal-utils'
import { import {
adaptForAppRouterInstance, adaptForAppRouterInstance,
adaptForPathname,
adaptForSearchParams, adaptForSearchParams,
PathnameContextProviderAdapter,
} from '../shared/lib/router/adapters' } from '../shared/lib/router/adapters'
import { AppRouterContext } from '../shared/lib/app-router-context' import { AppRouterContext } from '../shared/lib/app-router-context'
import { import { SearchParamsContext } from '../shared/lib/hooks-client-context'
PathnameContext,
SearchParamsContext,
} from '../shared/lib/hooks-client-context'
let tryGetPreviewData: typeof import('./api-utils/node').tryGetPreviewData let tryGetPreviewData: typeof import('./api-utils/node').tryGetPreviewData
let warn: typeof import('../build/output/log').warn let warn: typeof import('../build/output/log').warn
...@@ -621,7 +618,10 @@ export async function renderToHTML( ...@@ -621,7 +618,10 @@ export async function renderToHTML(
const AppContainer = ({ children }: { children: JSX.Element }) => ( const AppContainer = ({ children }: { children: JSX.Element }) => (
<AppRouterContext.Provider value={appRouter}> <AppRouterContext.Provider value={appRouter}>
<SearchParamsContext.Provider value={adaptForSearchParams(router)}> <SearchParamsContext.Provider value={adaptForSearchParams(router)}>
<PathnameContext.Provider value={adaptForPathname(asPath)}> <PathnameContextProviderAdapter
router={router}
isAutoExport={isAutoExport}
>
<RouterContext.Provider value={router}> <RouterContext.Provider value={router}>
<AmpStateContext.Provider value={ampState}> <AmpStateContext.Provider value={ampState}>
<HeadManagerContext.Provider <HeadManagerContext.Provider
...@@ -648,7 +648,7 @@ export async function renderToHTML( ...@@ -648,7 +648,7 @@ export async function renderToHTML(
</HeadManagerContext.Provider> </HeadManagerContext.Provider>
</AmpStateContext.Provider> </AmpStateContext.Provider>
</RouterContext.Provider> </RouterContext.Provider>
</PathnameContext.Provider> </PathnameContextProviderAdapter>
</SearchParamsContext.Provider> </SearchParamsContext.Provider>
</AppRouterContext.Provider> </AppRouterContext.Provider>
) )
......
import type { ParsedUrlQuery } from 'node:querystring' import type { ParsedUrlQuery } from 'node:querystring'
import { AppRouterInstance } from '../app-router-context' import React, { useMemo, useRef } from 'react'
import { NextRouter } from './router' import type { AppRouterInstance } from '../app-router-context'
import { PathnameContext } from '../hooks-client-context'
import type { NextRouter } from './router'
import { isDynamicRoute } from './utils'
/** /**
* adaptForAppRouterInstance implements the AppRouterInstance with a NextRouter. * adaptForAppRouterInstance implements the AppRouterInstance with a NextRouter.
...@@ -61,7 +64,9 @@ function transformQuery(query: ParsedUrlQuery): URLSearchParams { ...@@ -61,7 +64,9 @@ function transformQuery(query: ParsedUrlQuery): URLSearchParams {
* @param router the router that contains the query. * @param router the router that contains the query.
* @returns the search params in the URLSearchParams format * @returns the search params in the URLSearchParams format
*/ */
export function adaptForSearchParams(router: NextRouter): URLSearchParams { export function adaptForSearchParams(
router: Pick<NextRouter, 'isReady' | 'query'>
): URLSearchParams {
if (!router.isReady || !router.query) { if (!router.isReady || !router.query) {
return new URLSearchParams() return new URLSearchParams()
} }
...@@ -69,13 +74,56 @@ export function adaptForSearchParams(router: NextRouter): URLSearchParams { ...@@ -69,13 +74,56 @@ export function adaptForSearchParams(router: NextRouter): URLSearchParams {
return transformQuery(router.query) return transformQuery(router.query)
} }
/** export function PathnameContextProviderAdapter({
* adaptForPathname adapts the `asPath` parameter from the router to a pathname. children,
* router,
* @param asPath the asPath parameter to transform that comes from the router ...props
* @returns pathname part of `asPath` }: React.PropsWithChildren<{
*/ router: Pick<NextRouter, 'pathname' | 'asPath' | 'isReady' | 'isFallback'>
export function adaptForPathname(asPath: string): string { isAutoExport: boolean
const url = new URL(asPath, 'http://f') }>) {
return url.pathname const ref = useRef(props.isAutoExport)
const value = useMemo(() => {
// isAutoExport is only ever `true` on the first render from the server,
// so reset it to `false` after we read it for the first time as `true`. If
// we don't use the value, then we don't need it.
const isAutoExport = ref.current
if (isAutoExport) {
ref.current = false
}
// When the route is a dynamic route, we need to do more processing to
// determine if we need to stop showing the pathname.
if (isDynamicRoute(router.pathname)) {
// When the router is rendering the fallback page, it can't possibly know
// the path, so return `null` here. Read more about fallback pages over
// at:
// https://nextjs.org/docs/api-reference/data-fetching/get-static-paths#fallback-pages
if (router.isFallback) {
return null
}
// When `isAutoExport` is true, meaning this is a page page has been
// automatically statically optimized, and the router is not ready, then
// we can't know the pathname yet. Read more about automatic static
// optimization at:
// https://nextjs.org/docs/advanced-features/automatic-static-optimization
if (isAutoExport && !router.isReady) {
return null
}
}
// The `router.asPath` contains the pathname seen by the browser (including
// any query strings), so it should have that stripped. Read more about the
// `asPath` option over at:
// https://nextjs.org/docs/api-reference/next/router#router-object
const url = new URL(router.asPath, 'http://f')
return url.pathname
}, [router.asPath, router.isFallback, router.isReady, router.pathname])
return (
<PathnameContext.Provider value={value}>
{children}
</PathnameContext.Provider>
)
} }
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