useHydrated
TheuseHydrated hook helps you safely handle client-side only code and prevent hydration mismatches in server-rendered applications. It returns a boolean indicating whether the component has completed hydration.
Installation
Import
Usage
Returns
boolean
A boolean value that is
false during server-side rendering and initial render, and true after the component has hydrated on the client.Type Definition
Examples
Preventing Hydration Mismatches
Browser-Only Features
Local Storage Access
Conditional Client-Side Rendering
User Agent Detection
Media Query with SSR
Common Patterns
Progressive Enhancement
Start with a basic experience and enhance it after hydration:Avoiding Flash of Wrong Content
Use a loading placeholder that matches the server-rendered content:Use Cases
- Preventing hydration mismatches when using browser APIs
- Safely accessing
window,document,navigator, etc. - Working with localStorage, sessionStorage, or cookies
- Implementing theme toggles that read from client storage
- Conditional rendering of client-only libraries
- Handling time-sensitive or user-specific content
- Progressive enhancement strategies
Notes
- The hook returns
falseduring server-side rendering (SSR) - The hook returns
falseon the initial client render to match the server-rendered HTML - The hook returns
trueafter theuseEffectruns, which happens after hydration - This pattern prevents React hydration warnings by ensuring the initial client render matches the server render
- Use this hook when you need to access browser-only APIs or render content that differs between server and client
- For optimal user experience, consider showing a loading state or skeleton instead of hiding content entirely