Next.js - usePathname() Function



The usePathname() Function

The Next.js usePathname() function is used to access the current URL path of the page. This function is only available in the client-side.

Syntax

The syntax for the usePathname() function is as follows:

'use client'

import { usePathname } from 'next/navigation'

const pathname = usePathname()

Parameters

The usePathname() function does not accept any parameters.

Return Value

The usePathname() function returns a string representing the current URL path of the page.

URL Returned value
/ '/'
/dashboard '/dashboard'
/dashboard?v=2 '/dashboard'
/blog/hello-world '/blog/hello-world'

Example 1

In the example below, we are using the usePathname() function to access the current URL path of the page and display it in the console.

'use client'
 
import { usePathname } from 'next/navigation'
 
export default function ExampleClientComponent() {
    const pathname = usePathname()
    
    console.log(pathname)
    
    return (<h1>Next.js usePathname Function</h1>)
}

Output

Next.js usePathname Function Example 1

Example 2

In the example below, we are using the usePathname() function to access the current URL path of the page and display it in the current page itself.

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

Output

Next.js usePathname Function Example 2
Advertisements