useHydrated hook provides a simple way to determine if a component has fully hydrated on the client side. This is essential for Next.js applications to prevent hydration mismatches when using browser APIs or storage.
Signature
Returns
falseduring SSR (Server-Side Rendering) and initial rendertrueafter the component has mounted on the client
Usage Example
Basic Usage
Why Use This Hook?
Problem: Hydration Mismatches
Next.js pre-renders components on the server, but browser APIs likelocalStorage, sessionStorage, and window don’t exist on the server:
Solution: Wait for Hydration
Common Use Cases
1. LocalStorage/SessionStorage Access
2. Window Object Access
3. User Preferences from Storage
4. Zustand Store with Persistence
How It Works
The hook uses a simple effect that runs only on the client:- Server Render:
hydrated = false, component renders with SSR-safe content - HTML Sent to Client: Browser receives pre-rendered HTML
- React Hydration Begins: React attaches event handlers
- useEffect Runs:
setHydrated(true)is called - Component Re-renders: Now safe to use browser APIs
Preventing Content Flash
Method 1: Show Loading State
Method 2: Hide Until Hydrated
Method 3: Conditional Rendering
Best Practices
Always Use with Client Components
Always Use with Client Components
Add
'use client' directive at the top of files using this hook:Combine with useEffect
Combine with useEffect
Access storage inside effects, not during render:
Provide Fallback UI
Provide Fallback UI
Always render something during SSR:
Use for Zustand Persist
Use for Zustand Persist
Prevent mismatches when using Zustand’s persist middleware:
Alternative: Next.js dynamic Import
For components that should never render on the server:- dynamic: Entire component is client-only (e.g., map, chart library)
- useHydrated: Component renders on server but needs client-specific data
Complete Example
Related
- Tweaks Store - Uses persistence that benefits from this hook
- Favorite Store - Persists to localStorage
- usePokeFilters Hook - May need hydration check for persisted filters