How to Use usePathname Hook in Next.js for Current URL Path
In Next.js, you can use the
usePathname hook from the next/navigation module to get the current URL path inside a client component. This hook returns a string representing the current pathname, which updates automatically when the route changes.Syntax
The usePathname hook is imported from next/navigation and used inside a client component to get the current URL path as a string.
const pathname = usePathname();— returns the current path like"/about"or"/products/123".- Must be used in a React component marked with
"use client"because it relies on client-side navigation.
tsx
'use client'; import { usePathname } from 'next/navigation'; export default function MyComponent() { const pathname = usePathname(); return <div>Current path: {pathname}</div>; }
Output
Current path: /your-current-path
Example
This example shows a simple Next.js client component that displays the current URL path using usePathname. The path updates automatically when you navigate to different pages.
tsx
'use client'; import { usePathname } from 'next/navigation'; export default function ShowPath() { const pathname = usePathname(); return ( <main style={{ padding: '1rem', fontFamily: 'Arial, sans-serif' }}> <h1>Current Pathname</h1> <p>The current URL path is: <strong>{pathname}</strong></p> </main> ); }
Output
Current Pathname
The current URL path is: / (or current path)
Common Pitfalls
- Not using
"use client"directive:usePathnameonly works in client components. Forgetting"use client"causes errors. - Using in server components: This hook cannot be used in server components because it depends on client-side routing.
- Expecting full URL:
usePathnamereturns only the path part, not the full URL with domain or query parameters.
tsx
/* Wrong: Missing 'use client' */ import { usePathname } from 'next/navigation'; export default function WrongComponent() { const pathname = usePathname(); // This will error return <div>{pathname}</div>; } /* Right: Add 'use client' */ 'use client'; import { usePathname } from 'next/navigation'; export default function RightComponent() { const pathname = usePathname(); return <div>{pathname}</div>; }
Quick Reference
usePathname Hook Summary:
- Import from
next/navigation - Use only in client components (
"use client") - Returns current URL path as a string
- Updates automatically on route change
Key Takeaways
Always add 'use client' at the top of your component to use usePathname.
usePathname returns only the path part of the URL, not the full URL.
It updates automatically when the user navigates to a new page.
Do not use usePathname in server components; it works only on the client side.
Import usePathname from 'next/navigation' to access the current path.