[]previous and next page

hydrate

Attaches the application to HTML the server already rendered into container.

Attaches the application to HTML the server already rendered into container. Elements are claimed by their data-hk keys instead of created, so the DOM is not rebuilt and nodes keep their identity. Event handlers and reactive bindings are attached; markers are removed. Parts the server and client disagree on are repaired by reconciliation, never left half hydrated.

Import#

ts
import { hydrate } from "@shadow-js/web";

Signature#

ts
function hydrate(
  code: () => unknown,
  container: Element | Document,
  options: HydrateOptions = {},
): () => void

Parameters#

Name Description
code Runs once, untracked, and builds the same component tree the server rendered.
container Element or Document that holds the server markup.
options renderId (must match the server), the server's resource data, an owner, and the error reporters. Undefined uses the defaults.

Returns#

A dispose function that stops the hydrated root and removes its nodes. Safe to call more than once.

Throws#

  • Error (production message SHADOW_HYDRATE_RUNNING) when called while another hydration pass is in progress.

Examples#

ts
import { createComponent, hydrate } from "@shadow-js/web";

function App() {
  return "Hello";
}

const container = document.getElementById("app") as Element;
const data = JSON.parse(document.getElementById("data")?.textContent ?? "{}") as Record<
  string,
  unknown
>;
const dispose = hydrate(() => createComponent(App, {}), container, { data });