Unverified Commit 7a76e9fa authored by Joseph's avatar Joseph Committed by GitHub

docs: rewrite+usePathname+prerender hydration error mitigation (#83462)

Closes:
https://linear.app/vercel/issue/DOC-5040/usepathname-and-rewrites
parent 98811027
......@@ -65,6 +65,7 @@ const pathname = usePathname()
```tsx filename="app/example-client-component.tsx" switcher
'use client'
import { useEffect } from 'react'
import { usePathname, useSearchParams } from 'next/navigation'
function ExampleClientComponent() {
......@@ -79,6 +80,7 @@ function ExampleClientComponent() {
```jsx filename="app/example-client-component.js" switcher
'use client'
import { useEffect } from 'react'
import { usePathname, useSearchParams } from 'next/navigation'
function ExampleClientComponent() {
......@@ -90,6 +92,56 @@ function ExampleClientComponent() {
}
```
### Avoid hydration mismatch with rewrites
When a page is pre-rendered, the HTML is generated for the source pathname. If the page is then reached through a rewrite using `next.config` or `Middleware`, the browser URL may differ, and `usePathname()` will read the rewritten pathname on the client.
To avoid hydration mismatches, design the UI so that only a small, isolated part depends on the client pathname. Render a stable fallback on the server and update that part after mount.
```tsx filename="app/example-client-component.tsx" switcher
'use client'
import { useEffect, useState } from 'react'
import { usePathname } from 'next/navigation'
export default function PathnameBadge() {
const pathname = usePathname()
const [clientPathname, setClientPathname] = useState('')
useEffect(() => {
setClientPathname(pathname)
}, [pathname])
return (
<p>
Current pathname: <span>{clientPathname}</span>
</p>
)
}
```
```jsx filename="app/example-client-component.js" switcher
'use client'
import { useEffect, useState } from 'react'
import { usePathname } from 'next/navigation'
export default function PathnameBadge() {
const pathname = usePathname()
const [clientPathname, setClientPathname] = useState('')
useEffect(() => {
setClientPathname(pathname)
}, [pathname])
return (
<p>
Current pathname: <span>{clientPathname}</span>
</p>
)
}
```
| Version | Changes |
| --------- | ------------------------- |
| `v13.0.0` | `usePathname` introduced. |
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment