usePathname

usePathname 是一個客戶端元件 (Client Component) 鉤子,可讓您讀取當前 URL 的路徑名稱 (pathname)

'use client'

import { usePathname } from 'next/navigation'

export default function ExampleClientComponent() {
  const pathname = usePathname()
  return <p>Current pathname: {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])
}
版本變更
v13.0.0引入 usePathname

On this page