← All lessons
How hydration works
HTML first, handlers later
Server
Browser
server.jsx
// the server renders HTML with the data in itconst html = renderToString(<Product />);res.send(page(html, '<script src="/app.js">'));client.jsx
import { hydrateRoot } from "react-dom/client";// render the same tree again, but reuse the DOMhydrateRoot(root, <Product />); function Product() { const [n, setN] = useState(0); return ( <> <p>{new Date().toLocaleTimeString()}</p> {/* different on the server and the client */} <button onClick={() => setN(n + 1)}> Add to cart · {n} </button> </> );}Click while it loads and count the lost clicks
Rain jacket
$49
clicks lost0
clicks handled0
interactive at
index.html
<!-- the HTML paints first --><button>Add to cart · 0</button><script src="/app.js" defer></script> // app.jshydrateRoot(root, <Product />);Islands hydrate only what needs it
Header12 KBneeds JS
Photo gallery25 KBneeds JS
Description30 KBneeds JS
Add to cart8 KBneeds JS
Reviews40 KBneeds JS
Footer6 KBneeds JS
JS shipped
hydrated
responds after
Mid phone, on a 1.6 Mbps connection
product.astro
---import Gallery from "./Gallery.jsx";import Cart from "./Cart.jsx";---<Header /> <!-- plain HTML, no JS --><Description /><Gallery client:visible /> <!-- hydrate when it scrolls into view --><Cart client:load /> <!-- hydrate as soon as the page loads -->client.jsx
// whole-page hydration: every component runshydrateRoot(document, <ProductPage />);Topics
Next: How lazy loading works
Open lesson