useIsHydrated is a hook that reliably determines whether a React component tree has been hydrated on the client side. This is useful for conditional rendering based on whether the app is running on the server or has been hydrated in the browser.
Installation
Function Signature
Return Value
Returns
false during server-side rendering and initial render on the client, and true after hydration is complete.Usage
Basic Example
Conditional Browser API Usage
Avoiding Hydration Mismatches
Progressive Enhancement
Conditional Third-Party Scripts
Implementation Details
The hook usesuseSyncExternalStore from React 18’s use-sync-external-store/shim package:
- Server/SSR: Returns
false(viagetServerSnapshot) - Client (after hydration): Returns
true(viagetSnapshot) - Subscribe function: Returns a no-op (the value never changes after initial hydration)
- No hydration warnings or mismatches
- Compatibility with React’s concurrent features
- Works consistently in both SSR and client-only scenarios
When to Use
Use this hook when you need to:- Conditionally render client-only features
- Access browser APIs safely
- Avoid SSR/hydration mismatches
- Implement progressive enhancement
- Initialize client-side libraries after hydration
Notes
This hook uses
useSyncExternalStore, which is part of React 18. The shim package ensures compatibility with React 17 and earlier versions.The hook returns
false on the server and during the initial render on the client, then switches to true after hydration. This ensures the server and client render the same content initially.Unlike checking
typeof window !== 'undefined', this hook correctly handles the hydration phase and doesn’t cause hydration mismatches.