usePathname

usePathname は、現在の URL の パス名 (pathname) を読み取ることができる クライアントコンポーネント (Client Component) 用フックです。

'use client'

import { usePathname } from 'next/navigation'

export default function ExampleClientComponent() {
  const pathname = usePathname()
  return <p>現在のパス名: {pathname}</p>
}
'use client'

import { usePathname } from 'next/navigation'

export default function ExampleClientComponent() {
  const pathname = usePathname()
  return <p>現在のパス名: {pathname}</p>
}

usePathname は意図的に クライアントコンポーネント (Client Component) での使用が必須となっています。クライアントコンポーネントは最適化されていないわけではなく、サーバーコンポーネント (Server Components) アーキテクチャの重要な一部であることに注意してください。

例えば、usePathname を使用したクライアントコンポーネントは、初期ページ読み込み時に HTML としてレンダリングされます。新しいルートにナビゲートする際、このコンポーネントを再取得する必要はありません。代わりに、コンポーネントは一度(クライアント JavaScript バンドル内で)ダウンロードされ、現在の状態に基づいて再レンダリングされます。

補足:

パラメータ

const pathname = usePathname()

usePathname はパラメータを取りません。

戻り値

usePathname は現在の URL のパス名を文字列で返します。例:

URL戻り値
/'/'
/dashboard'/dashboard'
/dashboard?v=2'/dashboard'
/blog/hello-world'/blog/hello-world'

使用例

ルート変更に応じて処理を実行

'use client'

import { usePathname, useSearchParams } from 'next/navigation'

function ExampleClientComponent() {
  const pathname = usePathname()
  const searchParams = useSearchParams()
  useEffect(() => {
    // ここで処理を実行...
  }, [pathname, searchParams])
}
'use client'

import { usePathname, useSearchParams } from 'next/navigation'

function ExampleClientComponent() {
  const pathname = usePathname()
  const searchParams = useSearchParams()
  useEffect(() => {
    // ここで処理を実行...
  }, [pathname, searchParams])
}
バージョン変更点
v13.0.0usePathname が導入されました。