Skip to content

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.

  1. Find the mismatch. In hamur dev a 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.
  2. Fix it by making both renders read the same value. useHydrated() is false on the server and in the hydration render and true once the app mounted, so a browser-only value waits for it. ClientOnly renders its fallback in both and its children after mount. useId() gives an id that is equal on both sides, where Math.random() would not be:
tsx
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>
  )
}
  1. For a value that must be right before the first paint, such as a theme class on <html>, use onPrehydrate or a useHead script with hydrationSafe on the attribute. The script runs before hydration, so there is no flash and no mismatch.
  2. 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.