useHydration
True once the component has mounted on the client.
useHydration() is false on the server and on the first render in the browser, then true. Branch on it for anything the server cannot know: the time zone, the language, a choice kept in localStorage, a store that rehydrates. Both renders agree, so React reports no hydration mismatch. Until it is true, render a placeholder of the same size, such as a @khaeli/skeleton, so nothing jumps.
A value only the browser knows
- Time zone
- Language
"use client"
import { Skeleton } from "@/components/ui/skeleton"
import { useHydration } from "@/hooks/use-hydration"
export default function UseHydrationAValueOnlyTheBrowserKnows() {
const hydrated = useHydration()
return (
<dl className="grid w-full max-w-xs grid-cols-[auto_1fr] items-center gap-x-6 gap-y-2">
<dt className="text-muted-foreground">Time zone</dt>
{/* The server cannot know these, so it renders a placeholder of the same size. */}
<dd>{hydrated ? Intl.DateTimeFormat().resolvedOptions().timeZone : <Skeleton className="h-5 w-32" />}</dd>
<dt className="text-muted-foreground">Language</dt>
<dd>{hydrated ? navigator.language : <Skeleton className="h-5 w-16" />}</dd>
</dl>
)
}
A stored choice
- Review the pricing page copy
- Confirm the launch date
- Send the release notes
"use client"
import { useState } from "react"
import { Label } from "@/components/ui/label"
import { Switch } from "@/components/ui/switch"
import { useHydration } from "@/hooks/use-hydration"
const KEY = "compact-rows"
export default function UseHydrationAStoredChoice() {
const hydrated = useHydration()
const [changed, setChanged] = useState<boolean | null>(null)
// Storage is read only once the page is live: the server and the first render both say off.
const compact = changed ?? (hydrated && window.localStorage.getItem(KEY) === "on")
return (
<div className="flex w-full max-w-xs flex-col gap-4">
<div className="flex items-center gap-2">
<Switch
id="hydration-compact-rows"
checked={compact}
disabled={!hydrated}
onCheckedChange={(next) => {
window.localStorage.setItem(KEY, next ? "on" : "off")
setChanged(next)
}}
/>
<Label htmlFor="hydration-compact-rows">Compact rows</Label>
</div>
<ul className="divide-y divide-border border-y border-border">
{["Review the pricing page copy", "Confirm the launch date", "Send the release notes"].map((task) => (
<li key={task} className={compact ? "py-1" : "py-3"}>
{task}
</li>
))}
</ul>
</div>
)
}
Installation
npx shadcn@latest add @khaeli/use-hydrationbunx --bun shadcn@latest add @khaeli/use-hydrationInstalls with
Nothing else. This item needs no other Registry item and no npm package.
Accessible name
- A control whose value is not known yet stays in the page,
disabled, with its label. It becomes usable in the same place once the value is read.
Registry JSON
The item as the shadcn CLI reads it, with every file it ships: https://ui.khaeli.com/r/use-hydration.json