usePathname

Returns the current pathname without query parameters or hash.

import { usePathname } from 'one'
export default function CurrentPath() {
const pathname = usePathname()
// URL: /blog/hello-world?ref=twitter#comments
// Returns: "/blog/hello-world"
return <Text>Current path: {pathname}</Text>
}

Common Uses

import { usePathname, Link } from 'one'
function NavLink({ href, children }) {
const pathname = usePathname()
const isActive = pathname === href
return (
<Link href={href} style={{ fontWeight: isActive ? 'bold' : 'normal' }} >
{children}
</Link>
)
}

Conditional Rendering

function Layout({ children }) {
const pathname = usePathname()
const showSidebar = !pathname.startsWith('/auth')
return (
<div>
{showSidebar && <Sidebar />}
{children}
</div>
)
}

Analytics

function PageTracker() {
const pathname = usePathname()
useEffect(() => {
analytics.trackPageView(pathname)
}, [pathname])
return null
}

What’s Not Included

The pathname does not include:

  • Query parameters (?foo=bar)
  • Hash fragments (#section)

For URL parameters, use useParams or useActiveParams.

Edit this page on GitHub.