Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Apply Next.js best practices for RSC boundaries, async APIs, routing, metadata, and optimization.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
hydration-error.md
1# Hydration Errors23Diagnose and fix React hydration mismatch errors.45## Error Signs67- "Hydration failed because the initial UI does not match"8- "Text content does not match server-rendered HTML"910## Debugging1112In development, click the hydration error to see the server/client diff.1314## Common Causes and Fixes1516### Browser-only APIs1718```tsx19// Bad: Causes mismatch - window doesn't exist on server20<div>{window.innerWidth}</div>2122// Good: Use client component with mounted check23'use client'24import { useState, useEffect } from 'react'2526export function ClientOnly({ children }: { children: React.ReactNode }) {27const [mounted, setMounted] = useState(false)28useEffect(() => setMounted(true), [])29return mounted ? children : null30}31```3233### Date/Time Rendering3435Server and client may be in different timezones:3637```tsx38// Bad: Causes mismatch39<span>{new Date().toLocaleString()}</span>4041// Good: Render on client only42'use client'43const [time, setTime] = useState<string>()44useEffect(() => setTime(new Date().toLocaleString()), [])45```4647### Random Values or IDs4849```tsx50// Bad: Random values differ between server and client51<div id={Math.random().toString()}>5253// Good: Use useId hook54import { useId } from 'react'5556function Input() {57const id = useId()58return <input id={id} />59}60```6162### Invalid HTML Nesting6364```tsx65// Bad: Invalid - div inside p66<p><div>Content</div></p>6768// Bad: Invalid - p inside p69<p><p>Nested</p></p>7071// Good: Valid nesting72<div><p>Content</p></div>73```7475### Third-party Scripts7677Scripts that modify DOM during hydration.7879```tsx80// Good: Use next/script with afterInteractive81import Script from 'next/script'8283export default function Page() {84return (85<Script86src="https://example.com/script.js"87strategy="afterInteractive"88/>89)90}91```92