Capítulo 186 de 456
Client Component hook that returns the current URL's pathname as a string. Reading the URL is intentionally not supported in Server Components, since that would break layout state preservation across navigations.
'use client'
import { usePathname } from 'next/navigation'
export default function ExampleClientComponent() {
const pathname = usePathname()
return <p>Current pathname: {pathname}</p>
}
| URL | Returned value |
|---|---|
/ | '/' |
/dashboard | '/dashboard' |
/dashboard?v=2 | '/dashboard' |
/blog/hello-world | '/blog/hello-world' |
usePathname() em página estaticamente prerenderizada com rewrites: pode causar hydration mismatch, pois o valor inicial vem do servidor (path de origem) e diverge do path reescrito no browser. Isole a leitura num componente pequeno que atualiza após o mount (useEffect).app e pages coexistem; o tipo de retorno se ajusta automaticamente.cacheComponents ativo, rotas com params dinâmicos não cobertos por generateStaticParams fazem usePathname suspender; precisa de Suspense.useSearchParams para reagir a qualquer mudança de rota via useEffect.