osgsm.io
HomeNotesNext.js の usePathname で URL のパス名を読み取る

Next.js の usePathname で URL のパス名を読み取る

Published Jan 31, 2025
Updated Feb 16, 2025

note

Using App Router

Next.js の usePathname は、現在の URL の pathname を読み取ることを可能にする Client Component hook。

'use client'
 
import { usePathname } from 'next/navigation'
 
export default function ExampleClientComponent() {
  const pathname = usePathname()
  return <p>Current pathname: {pathname}</p>
}

usePathname() は、引数を受け取らず、現在の pathname を string として返す。

URL と return value の対応は以下の通り。

URLReturn value
/'/'
/blog'/blog'
/blog?page=2'/blog'
/blog/hello-world'/blog/hello-world'

query string が URL に含まれる場合、それは return value には含まれない。


参考