The app router usePathname() hook in client component causes hydration error because the value on server render is always just '/' but on client is actual correct current path.
Minimal example code would be:
'use client'
import { usePathname } from 'next/navigation'
export default function UsePathname() {
const pathname = usePathname()
console.log(pathname)
return <div>{pathname}</div>
}
Browser console output:
[Log] pathname check – "/" (page.tsx, line 9)
[Log] pathname check – "/use_pathname" (page.tsx, line 9)
[Error] Error: Hydration failed because the server rendered text didn't match the client. As a result this tree will be regenerated on the client. This can happen if a SSR-ed Client Component used:
- A server/client branch `if (typeof window !== 'undefined')`.
- Variable input such as `Date.now()` or `Math.random()` which changes each time it's called.
- Date formatting in a user's locale which doesn't match the server.
- External changing data without sending a snapshot of it along with the HTML.
- Invalid HTML tag nesting.
It can also happen if the client has a browser extension installed which messes with the HTML before React loaded.
https://react.dev/link/hydration-mismatch
<LayoutSegmentProvider childSegments={[...]}>
<link>
<RemoveDuplicateServerCss>
<default>
<RootLayout>
<html lang="en" className="__variable...">
<body className="min-h-full...">
<meta>
<title>
<meta>
<meta>
<LayoutSegmentProvider childSegments={[...]}>
<UsePathname params={Promise} searchParams={Promise}>
<div>
+ /
- /use_pathname
reportError (react-dom_client.js:2967)
defaultOnRecoverableError (react-dom_client.js:5276)
runWithFiberInDEV (react-dom_client.js:850:132)
flushSpawnedWork (react-dom_client.js:8740)
commitRoot (react-dom_client.js:8584)
commitRootWhenReady (react-dom_client.js:8078)
performWorkOnRoot (react-dom_client.js:8050)
performWorkOnRootViaSchedulerTask (react-dom_client.js:9058)
performWorkUntilDeadline (react-dom_client.js:35)
I'm attaching minimal project with above code example.
Once vinext server is running (pnpm dev:vinext) open http://localhost:3001/use_pathname to reproduce the issue.
my-app.zip
The app router usePathname() hook in client component causes hydration error because the value on server render is always just '/' but on client is actual correct current path.
Minimal example code would be:
Browser console output:
I'm attaching minimal project with above code example.
Once vinext server is running (
pnpm dev:vinext) openhttp://localhost:3001/use_pathnameto reproduce the issue.my-app.zip