Che cos’è l’idratazione?
Articolo correlato: SSR vs CSR vs SSG vs ISR (EN).
Il server genera HTML che il browser analizza prima dell’avvio di React. L’idratazione collega il DOM esistente a un albero interattivo invece di ricostruire autonomamente l’applicazione. hydrateRoot richiede risultati iniziali coincidenti. Tratta le discrepanze come errori anche se React recupera con rendering client; non garantisce la correzione di ogni attributo. Next.js gestisce la radice, quindi non chiamare hydrateRoot manualmente. [1][7][9]
Individuare la vera causa
Esamina il messaggio, lo stack dei componenti, la risposta HTML in Network e il DOM prima dell’idratazione. Il parser può chiudere p prima di div o inserire tbody in una tabella; confrontare solo JSX non basta. I pulsanti annidati non sono validi. Date.now(), Math.random(), un ramo typeof window durante il rendering e dati diversi possono creare alberi divergenti. Riproduci con un profilo pulito: estensioni e trasformazioni HTML del CDN possono cambiare il risultato. [2][3][10][12]
Un’unica istantanea di dati e tempo
src/snapshot.ts
export interface Snapshot {
generatedAt: string;
label: string;
}
function isObject(value: unknown): value is object {
if (value === null) {
return false;
}
return typeof value === "object";
}
function isCanonicalInstant(value: unknown): value is string {
if (typeof value !== "string") {
return false;
}
const milliseconds = Date.parse(value);
if (!Number.isFinite(milliseconds)) {
return false;
}
return new Date(milliseconds).toISOString() === value;
}
function isNonEmptyText(value: unknown): value is string {
if (typeof value !== "string") {
return false;
}
return value.trim().length > 0;
}
export function parseSnapshot(raw: string): Snapshot {
const value: unknown = JSON.parse(raw);
if (!isObject(value)) {
throw new TypeError("Expected a snapshot object.");
}
if (!("generatedAt" in value)) {
throw new TypeError("Missing timestamp.");
}
if (!("label" in value)) {
throw new TypeError("Missing label.");
}
if (!isCanonicalInstant(value.generatedAt)) {
throw new TypeError("Invalid timestamp.");
}
if (!isNonEmptyText(value.label)) {
throw new TypeError("Invalid label.");
}
return {
generatedAt: value.generatedAt,
label: value.label,
};
}
export function createSnapshot(now: Date): Snapshot {
const generatedAt = now.toISOString();
const formatter = new Intl.DateTimeFormat("en-GB", {
dateStyle: "medium",
timeStyle: "short",
timeZone: "UTC",
});
return {
generatedAt,
label: `${formatter.format(now)} UTC`,
};
}
export function serializeSnapshot(snapshot: Snapshot): string {
return JSON.stringify(snapshot).replaceAll("<", "\\u003c");
}
Articolo correlato: JavaScript Date, Intl i Temporal (EN).
Non calcolare indipendentemente l’ora di generazione, il numero di prodotti o un ID casuale sul server e sul client. Crea un’istantanea pubblica per richiesta e passa gli stessi dati a entrambi i rendering. UTC e locale espliciti riducono le differenze, ma versioni di ICU possono formattare diversamente; trasmetti quindi l’etichetta già formattata. Il parser accetta l’output canonico di toISOString e rifiuta date invalide ed etichette vuote. Non valida ogni formato ISO 8601. [1][15]
Trasporto sicuro dello stato SSR
src/server.tsx
import { createServer } from "node:http";
import { readFile } from "node:fs/promises";
import { renderToString } from "react-dom/server";
import { App } from "./app";
import { createSnapshot, serializeSnapshot } from "./snapshot";
const PORT = 4173;
function renderPage(): string {
const snapshot = createSnapshot(new Date());
const markup = renderToString(<App snapshot={snapshot} />);
const data = serializeSnapshot(snapshot);
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Hydration lab</title>
<link rel="stylesheet" href="/it/styles.css">
</head>
<body>
<div id="root">${markup}</div>
<script id="initial-data" type="application/json">${data}</script>
<script type="module" src="/client.js"></script>
</body>
</html>`;
}
const assets = new Map<string, readonly [string, string]>([
["/client.js", ["dist/client.js", "text/javascript"]],
["/styles.css", ["src/styles.css", "text/css"]],
]);
createServer(async (request, response) => {
try {
if (request.method !== "GET") {
response.writeHead(405, { Allow: "GET" }).end();
return;
}
const path = request.url ?? "/";
if (path === "/") {
const html = renderPage();
response.writeHead(200, {
"Content-Type": "text/html; charset=utf-8",
"Cache-Control": "no-store",
});
response.end(html);
return;
}
const asset = assets.get(path);
if (!asset) {
response.writeHead(404).end();
return;
}
const [filename, type] = asset;
const content = await readFile(filename);
response.writeHead(200, { "Content-Type": type });
response.end(content);
} catch (error) {
console.error(error);
if (response.headersSent) {
response.destroy();
return;
}
response.writeHead(500).end("Internal error");
}
}).listen(PORT, "127.0.0.1");
src/client.tsx
import { hydrateRoot } from "react-dom/client";
import { App } from "./app";
import { parseSnapshot } from "./snapshot";
const root = document.getElementById("root");
const data = document.getElementById("initial-data");
if (!(root instanceof HTMLElement)) {
throw new Error("Missing application root.");
}
if (!(data instanceof HTMLScriptElement)) {
throw new Error("Missing initial snapshot.");
}
const snapshot = parseSnapshot(data.textContent ?? "");
hydrateRoot(root, <App snapshot={snapshot} />, {
onRecoverableError(error, info) {
console.error("Recoverable React error", error, info.componentStack);
},
});
Il laboratorio usa renderToString per una piccola pagina senza sospensione Suspense. I dati sono in uno script application/json; il client legge textContent, valida la struttura e invoca hydrateRoot. Sostituire il carattere minore di con una sequenza Unicode impedisce ai dati di chiudere lo script; JSON.stringify da solo non basta. Non esporre segreti nell’HTML. In produzione preferisci serializzazione e streaming del framework. Segnala errori recuperabili senza dati privati. [1][9][10][14]
Stato del browser e useSyncExternalStore
src/use-dark-preference.ts
import { useSyncExternalStore } from "react";
const QUERY = "(prefers-color-scheme: dark)";
function subscribe(notify: () => void): () => void {
const media = window.matchMedia(QUERY);
media.addEventListener("change", notify);
return () => {
media.removeEventListener("change", notify);
};
}
function getSnapshot(): boolean {
return window.matchMedia(QUERY).matches;
}
function getServerSnapshot(): null {
return null;
}
export function useDarkPreference(): boolean | null {
return useSyncExternalStore<boolean | null>(
subscribe,
getSnapshot,
getServerSnapshot,
);
}
Non leggere matchMedia o localStorage durante il normale rendering server. L’hook restituisce null durante SSR e idratazione, poi legge la preferenza effettiva. La sottoscrizione stabile rimuove il listener alla cancellazione. Un’istantanea oggetto deve mantenere identità finché i dati non cambiano. In alternativa leggi in useEffect dopo l’idratazione, considerando rendering aggiuntivo, sfarfallio ed errori localStorage. Per il tema visivo spesso basta CSS prefers-color-scheme. [5][6]
Identificatori, stato e semantica
src/app.tsx
import { useId, useState } from "react";
import type { Snapshot } from "./snapshot";
import { useDarkPreference } from "./use-dark-preference";
interface AppProps {
snapshot: Snapshot;
}
function describePreference(value: boolean | null): string {
if (value === null) {
return "Checking browser preference";
}
return value ? "Dark preference" : "Light preference";
}
export function App({ snapshot }: AppProps) {
const inputId = useId();
const darkPreference = useDarkPreference();
const [count, setCount] = useState(0);
function increment(): void {
setCount((previous) => previous + 1);
}
return (
<main>
<h1>Hydration lab</h1>
<p>
Generated: {" "}
<time dateTime={snapshot.generatedAt}>{snapshot.label}</time>
</p>
<p>{describePreference(darkPreference)}</p>
<label htmlFor={inputId}>Note</label>
<input id={inputId} name="note" />
<button type="button" onClick={increment}>
Increment
</button>
<p role="status">Count: {count}</p>
</main>
);
}
src/styles.css
:root {
color-scheme: light dark;
font-family: system-ui, sans-serif;
}
main {
max-width: 40rem;
margin: 4rem auto;
padding: 1rem;
display: grid;
gap: 1rem;
}
input,
button {
font: inherit;
padding: 0.75rem;
}
:focus-visible {
outline: 3px solid Highlight;
outline-offset: 3px;
}
Articolo correlato: React Rendering and Reconciliation (EN).
useId collega label e input se gli alberi coincidono. Non è destinato a chiavi di liste o ID di entità. Con radici indipendenti scegli identifierPrefix distinti, uguali sul server e client per ogni radice. Il laboratorio condivide App, contatore iniziale 0 ed etichetta temporale. Un clic incrementa il contatore; elementi semantici consentono di testare il comportamento senza leggere lo stato interno. [4][1]
Next.js: confini ed eccezioni
next-example/app/page.tsx
import { createSnapshot } from "../src/snapshot";
import { ClientApp } from "./client-app";
export default function Page() {
const publishedAt = new Date("2026-11-27T10:00:00.000Z");
const snapshot = createSnapshot(publishedAt);
return <ClientApp snapshot={snapshot} />;
}
next-example/app/client-app.tsx
"use client";
import { App } from "../src/app";
import type { Snapshot } from "../src/snapshot";
interface ClientAppProps {
snapshot: Snapshot;
}
export function ClientApp({ snapshot }: ClientAppProps) {
return <App snapshot={snapshot} />;
}
Articolo correlato: React Server Components vs Client Components (EN).
use client definisce un confine tra moduli, non disattiva automaticamente il prerendering HTML. Passa dati serializzabili da Server Components e allinea la cache iniziale delle query. dynamic con ssr: false può isolare una libreria dipendente dal DOM in un Client Component, a scapito dell’HTML iniziale. suppressHydrationWarning è un’eccezione limitata a un livello per differenze inevitabili, non una riparazione ricorsiva; React non corregge così il testo divergente. Non sopprimere globalmente su html. [1][2][7][8][16]
Copia la variante Next.js in un progetto App Router separato secondo README. La data fissa rappresenta un record di esempio, non l’ora della richiesta. Il framework trasferisce l’istantanea; non copiare il punto di ingresso hydrateRoot personalizzato. [1][2][7][8][16]
Test di regressione Given-When-Then
npm install
npm run typecheck
npm run test:unit
npm run build
npx playwright install chromium
npm run test:e2e
tests/snapshot.test.cjs
const { test } = require("node:test");
const assert = require("node:assert/strict");
const {
createSnapshot,
parseSnapshot,
serializeSnapshot,
} = require("../dist-unit/snapshot.js");
const instant = "2026-11-27T10:00:00.000Z";
const snapshot = { generatedAt: instant, label: "27 Nov 2026 UTC" };
test("Given a valid snapshot, serialization preserves the values", () => {
// Given
const raw = serializeSnapshot(snapshot);
// When
const result = parseSnapshot(raw);
// Then
assert.deepEqual(result, snapshot);
});
test("Given script-closing text, JSON cannot close the script", () => {
// Given
const value = { ...snapshot, label: "</script><script>alert(1)" };
// When
const raw = serializeSnapshot(value);
// Then
assert.equal(raw.includes("<"), false);
assert.deepEqual(parseSnapshot(raw), value);
});
const invalid = [
"null",
"[]",
"42",
"{}",
"{",
JSON.stringify({ ...snapshot, generatedAt: "2026-11-27" }),
JSON.stringify({ ...snapshot, generatedAt: "invalid" }),
JSON.stringify({ ...snapshot, generatedAt: "2026-02-30T00:00:00.000Z" }),
JSON.stringify({ ...snapshot, label: " " }),
JSON.stringify({ ...snapshot, label: 5 }),
];
for (const [index, raw] of invalid.entries()) {
test(`Given invalid snapshot ${index + 1}, parsing rejects it`, () => {
// When / Then
assert.throws(() => parseSnapshot(raw));
});
}
test("Given a fixed date, the initial label uses UTC", () => {
// Given
const now = new Date(instant);
// When
const result = createSnapshot(now);
// Then
assert.equal(result.generatedAt, instant);
assert.match(result.label, /UTC$/);
});
tests/hydration.spec.ts
import { expect, test } from "@playwright/test";
for (const timeZone of ["Europe/Warsaw", "America/New_York"]) {
test.describe(timeZone, () => {
test.use({ timezoneId: timeZone, colorScheme: "dark" });
test("initial HTML hydrates and remains interactive", async ({
page,
}) => {
// Given
const errors: string[] = [];
page.on("pageerror", (error) => errors.push(error.message));
page.on("console", (message) => {
if (message.type() === "error") {
errors.push(message.text());
}
});
// When
const response = await page.goto("/");
// Then
if (!response) {
throw new Error("Missing navigation response.");
}
expect(response.ok()).toBe(true);
const html = await response.text();
expect(html).toContain("Checking browser preference");
await expect(page.getByText("Dark preference")).toBeVisible();
const initialTime = html.match(/<time[^>]*>([^<]+)<\/time>/);
if (!initialTime) {
throw new Error("Missing server time label.");
}
const label = initialTime[1];
if (label === undefined) {
throw new Error("Missing server time text.");
}
await expect(page.locator("time")).toHaveText(label);
await page.getByLabel("Note").fill("Hydrated");
await page.getByRole("button", { name: "Increment" }).click();
await expect(page.getByRole("status")).toHaveText("Count: 1");
expect(errors).toEqual([]);
});
});
}
test("reports a deliberately changed client snapshot", async ({ page }) => {
// Given
const label = "Different client label";
const recoveryErrors: string[] = [];
page.on("console", (message) => {
if (message.text().startsWith("Recoverable React error")) {
recoveryErrors.push(message.text());
}
});
await page.route("**/", async (route) => {
const response = await route.fetch();
const original = await response.text();
const body = original.replace(
/"label":"[^"]*"/,
`"label":${JSON.stringify(label)}`,
);
expect(body).not.toBe(original);
await route.fulfill({ response, body });
});
// When
await page.goto("/");
// Then
await expect(page.locator("time")).toHaveText(label);
await expect.poll(() => recoveryErrors.length).toBeGreaterThan(0);
});
playwright.config.ts
import { defineConfig } from "@playwright/test";
export default defineConfig({
testDir: "./tests",
use: { baseURL: "http://127.0.0.1:4173" },
webServer: {
command: "npm run serve",
url: "http://127.0.0.1:4173",
reuseExistingServer: false,
},
});
Avvia il laboratorio seguendo README. Node.js verifica il contratto dell’istantanea, dati errati e protezione dalla chiusura dello script. Playwright registra pageerror e console.error prima della navigazione, confronta l’etichetta temporale della risposta HTML e verifica preferenza scura e interazione con il modulo. Ripeti con fusi diversi, JavaScript lento e build di produzione. Oltre all’assenza di errori, verifica un’azione riuscita. I test del parser non provano da soli l’idratazione. [11][13]
L’ultimo test modifica deliberatamente solo l’etichetta JSON, mantenendo l’HTML server. Attende un evento di recupero e la nuova etichetta. È una regressione controllata, non codice di produzione. [11][13]
Diagnostica in produzione e distribuzione
Se il problema appare solo dopo il deploy, controlla allineamento di HTML, manifest e JavaScript, regole CDN, Service Worker e chiavi cache per lingua e personalizzazione. Non servire HTML privato da cache condivisa. React 19 mostra dettagli più chiari; onRecoverableError registra i recuperi in una radice gestita direttamente, ma non ogni avviso. Raccogli l’ID di versione e contesto depurato, non tutto l’HTML dell’utente. Correggi la causa e misura l’interattività. [1][2][12]
