usePathname
usePathnameは、現在のURLのpathnameを読み取ることができるClient Componentフックです。
- TypeScript
- JavaScript
app/example-client-component.tsx
'use client'
import { usePathname } from 'next/navigation'
export default function ExampleClientComponent() {
const pathname = usePathname()
return <p>Current pathname: {pathname}</p>
}
app/example-client-component.js
'use client'
import { usePathname } from 'next/navigation'
export default function ExampleClientComponent() {
const pathname = usePathname()
return <p>Current pathname: {pathname}</p>
}
usePathnameは意図的にClient Componentを使用する必要があります。Client Componentは非最適化ではなく、Server Componentsアーキテクチャの重要な部分であることに注意してください。
例えば、usePathnameを持つClient Componentは、初回のページロード時にHTMLにレンダリングされます。新しいルートに移動する際、このコンポーネントは再取得する必要がありません。代わりに、コンポーネントは一度(クライアントのJavaScriptバンドル内で)ダウンロードされ、現在の状態に基づいて再レンダリングされます。
Good to know:
- Server Componentから現在のURLを読み取ることはサポートされていません。この設計は、ページナビゲーションをまたいでレイアウト状態を保持するために意図されています。
- 互換モード:
- fallback routeがレンダリングされている場合や、
pagesディレクトリのページがNext.jsによって自動的に静的最適化されており、ルーターが準備できていない場合、usePathnameはnullを返すことがあります。next.configやMiddlewareでリライトを使用する際、useStateとuseEffectも使用して、ハイドレーションの不一致エラーを避ける必要があります。- プロジェクトに
appディレクトリとpagesディレクトリの両方が存在する場合、Next.jsは自動的に型を更新します。
パラメータ
const pathname = usePathname()
usePathnameはパラメータを受け取りません。
戻り値
usePathnameは現在のURLのpathnameの文字列を返します。例えば:
| URL | 戻り値 |
|---|---|
/ | '/' |
/dashboard | '/dashboard' |
/dashboard?v=2 | '/dashboard' |
/blog/hello-world | '/blog/hello-world' |
例
ルート変更に応じて何かを行う
- TypeScript
- JavaScript
app/example-client-component.tsx
'use client'
import { usePathname, useSearchParams } from 'next/navigation'
function ExampleClientComponent() {
const pathname = usePathname()
const searchParams = useSearchParams()
useEffect(() => {
// ここで何かを行います...
}, [pathname, searchParams])
}
app/example-client-component.js
'use client'
import { usePathname, useSearchParams } from 'next/navigation'
function ExampleClientComponent() {
const pathname = usePathname()
const searchParams = useSearchParams()
useEffect(() => {
// ここで何かを行います...
}, [pathname, searchParams])
}
| バージョン | 変更点 |
|---|---|
v13.0.0 | usePathnameが導入されました。 |