Hydration
Goal: the first render in the browser produces the markup the server sent, so the library attaches to it without repairing anything. A mismatch comes from a value that differs between the two: Date.now(), Math.random(), a typeof window branch, a locale, or a browser extension that edits the page.
- Find the mismatch. In
hamur deva page whose first browser render differs from the server's HTML is reported, the same for all six adapters: a line in the browser console and the terminal, and by default a panel with the server's and the client's markup side by side. See Debugging. - Fix it by making both renders read the same value.
useHydrated()isfalseon the server and in the hydration render andtrueonce the app mounted, so a browser-only value waits for it.ClientOnlyrenders itsfallbackin both and its children after mount.useId()gives an id that is equal on both sides, whereMath.random()would not be:
import { ClientOnly, useHydrated, useId } from "@hamur/adapter-react"
export default function Footer() {
const hydrated = useHydrated()
const id = useId()
return (
<footer>
<label htmlFor={id}>Time zone</label>
<output id={id}>{hydrated ? Intl.DateTimeFormat().resolvedOptions().timeZone : "UTC"}</output>
<ClientOnly fallback={<span>Loading the clock</span>}>
<time>{new Date().toLocaleTimeString()}</time>
</ClientOnly>
</footer>
)
}
- For a value that must be right before the first paint, such as a theme class on
<html>, useonPrehydrateor auseHeadscript withhydrationSafeon the attribute. The script runs before hydration, so there is no flash and no mismatch. - For a part that never needs to run in the browser, make it a server-only component (
<Name>.server.<ext>): it is rendered on the server and never hydrated.
A page that uses useState or useAsyncData needs none of this for its data: the value computed on the server travels in the payload, and the browser starts from it.
See also: Islands and streaming, Dev server, State.