Server rendering and hydration
How React apps reach the browser as HTML and become interactive: CSR, SSR, static and streaming rendering, what hydration does, why mismatches happen and how to fix them, selective hydration and the cost of the interactivity gap.
This topic starts at Middle level.
CSR, SSR, static and streaming rendering
Eyni React tətbiqi brauzerə bir neçə yolla çata bilər. Onları ayıran əsas sual budur: ilk HTML harada və nə vaxt yaranır? İstifadəçinin əvvəlcə nə görəcəyi və səhifənin nə vaxt reaksiya verəcəyi məhz bundan asılıdır.
- Client-side rendering (CSR). Server demək olar ki, boş
<div id="root"></div>və bir bundle göndərir. Brauzer JavaScript-i yükləyib icra edir, data-nı gətirir və yalnız bundan sonracreateRootilə DOM-u qurur. Hosting ucuzdur, amma və həm bundle-ı, həm data-nı gözləyir; tətbiq böyüdükcə input-la yarışan JavaScript də artır (INP). - Server-side rendering (SSR). Server hər sorğuda komponentləri HTML-ə render edir. Brauzer məzmunu heç bir skript işləmədən çəkir, sonra onu interaktiv edir. Render hər sorğuda server vaxtı aparır və bu, TTFB-ni artıra bilər.
- Statik render (SSG). HTML build zamanı, hər URL üçün ayrıca fayl kimi yaranır və CDN-dən verilir. TTFB həmişə qısadır, hər sorğuda server işi yoxdur, amma səhifə son build qədər təzədir, istifadəçiyə xas hər şey isə yenə brauzerdə render olunmalıdır.
- Streaming SSR. Server HTML-i hissə-hissə göndərir: əvvəlcə
<Suspense>fallback-ləri olan shell-i, sonra hər yavaş hissəni data-sı hazır olanda. İlk baytlar artıq ən yavaş sorğunu gözləmir.
| İlk HTML | TTFB | FCP / LCP | İnteraktivlik | Xərc | |
|---|---|---|---|---|---|
| CSR | boş shell | qısa | gec: JS və data-dan sonra | bundle işləyəndən sonra | statik hosting |
| SSR | hər sorğuda tam səhifə | daha uzun: əvvəlcə server render edir | erkən | hydration-dan sonra | hər sorğuda server işi |
| SSG | build-dən gələn tam səhifə | qısa, CDN-dən | erkən | hydration-dan sonra | yenidən build; arada köhnəlir |
| Streaming SSR | əvvəlcə shell, qalanı hissə-hissə | qısa | shell üçün erkən | sərhəd-sərhəd | hər sorğuda server işi |
İki məqamı gözdən qaçırmaq asandır. Birincisi, SSR və SSG JavaScript-i aradan qaldırmır: hydration üçün brauzer yenə eyni komponentləri yükləyib icra edir. web.dev-in "Rendering on the Web" məqaləsi xəbərdarlıq edir ki, çox vaxt eyni tətbiqi iki dəfə — bir dəfə serverdə, bir dəfə client-də — qurmuş olursan. İkincisi, bu seçim bütün tətbiq üçün yox, hər route üçün edilir: marketinq səhifəsi statik, məhsul səhifəsi streaming, redaktor isə client-də render oluna bilər.
renderToString hələ də işləyir, amma nəticəni dərhal sətir kimi qaytarır: nə stream edir, nə də data-nı gözləyir. Yeni kod üçün react.dev renderToPipeableStream (Node.js stream-ləri) və renderToReadableStream (Web Streams: Deno, edge runtime-lar), statik generasiya üçün isə prerender / prerenderToNodeStream tövsiyə edir.
The same React app can reach the browser in several ways. They differ in where and when the first HTML is produced, and that decides what the user sees first and when the page responds.
- Client-side rendering (CSR). The server sends an almost empty
<div id="root"></div>and a bundle. The browser downloads and runs the JavaScript, fetches the data and only then builds the DOM withcreateRoot. Hosting is cheap, but and wait for the bundle and the data, and as the app grows, so does the JavaScript that competes with input (INP). - Server-side rendering (SSR). For every request the server renders the components to HTML. The browser paints the content before any script runs; then makes it interactive. Rendering takes server time on each request, which can raise TTFB.
- Static rendering (SSG). The HTML is rendered at build time, one file per URL, and served from a CDN. TTFB is consistently fast and there is no per-request server work, but the page is only as fresh as the last build, and anything per-user still has to be rendered in the browser.
- Streaming SSR. The server sends HTML in chunks: first the shell of the page with
<Suspense>fallbacks, then each slow part when its data is ready. The first bytes no longer wait for the slowest query.
| First HTML | TTFB | FCP / LCP | Interactive | Cost | |
|---|---|---|---|---|---|
| CSR | empty shell | fast | late: after JS and data | when the bundle has run | static hosting |
| SSR | full page per request | slower: server renders first | early | after hydration | server work per request |
| SSG | full page from the build | fast, from a CDN | early | after hydration | rebuilds; stale between them |
| Streaming SSR | shell first, rest in chunks | fast | early for the shell | boundary by boundary | server work per request |
Two things are easy to miss. First, SSR and SSG do not remove JavaScript: to hydrate, the browser still downloads and runs the same components. web.dev's "Rendering on the Web" warns that you are often building the same app twice, once on the server and once on the client. Second, these are per-route choices, not per-app ones: a marketing page can be static, a product page streamed, and an editor client-rendered.
renderToString still works, but it returns a string at once: it neither streams nor waits for data. For new code react.dev points to renderToPipeableStream (Node.js streams) and renderToReadableStream (Web Streams: Deno, edge runtimes), and to prerender / prerenderToNodeStream for static generation.
What hydration does
Hydration server HTML-ini yenidən qurmadan interaktiv edir. hydrateRoot(domNode, reactNode) komponent ağacını brauzerdə adi qaydada render edir, amma DOM node-ları yaratmaq əvəzinə sənəddə artıq olan node-ları gəzir, onları eyni ardıcıllıqla bir-bir "mənimsəyir" və event handler-ləri bağlayır. Bu iş bitəndə root client-də render olunmuş istənilən root kimi davranır.
import { renderToPipeableStream } from "react-dom/server";
import { App } from "./App";
app.get("/products", (req, res) => {
const { pipe } = renderToPipeableStream(<App />, {
bootstrapScripts: ["/client.js"],
onShellReady() {
res.setHeader("Content-Type", "text/html");
pipe(res);
},
});
});import { hydrateRoot } from "react-dom/client";
import { App } from "./App";
hydrateRoot(document, <App />);Burada App bütün <html> sənədini render edir, ona görə client document-i hydrate edir. Server HTML ilə birlikdə client.js-i yükləyən <script> göndərir; brauzer HTML-i dərhal çəkir, skripti isə gələndə icra edir.
Ağac eyni olmalıdır
Hydration "fərqi tap və düzəlt" addımı deyil. React fərz edir ki, client-dəki ilk render serverin verdiyi nəticənin eynisini verəcək; react.dev hər uyğunsuzluğu bug kimi qəbul etməyi tələb edir. Heç nəyin fərqlənmədiyi adi halda hər node-un hər atributunu yoxlamaq hydration-u çox yavaşladardı, ona görə React bunu etmir.
Deməli, ilk client render yalnız serverdə də olan şeylərdən istifadə edə bilər:
- eyni komponentlər və eyni props;
- eyni data — framework-lər onu səhifəyə serializasiya edir (JSON skripti və ya Server Components payload-u), ki client onu yenidən sorğulamasın;
- yalnız brauzerdə olan giriş dəyərləri yox:
localStorage,window.matchMedia, cihazın saat qurşağı, təsadüfi ədəd.
Qiyməti
Hydration DOM node-larının yaradılmasını ötürür, render-i yox. Səhifədəki hər komponent yenə yüklənməli, təhlil olunmalı və bir dəfə icra olunmalıdır. Bu iş bitənə qədər səhifə hazır görünür, amma React-in event handler-ləri hələ bağlanmayıb. Bu boşluq və onu necə kiçiltmək aşağıdakı senior bölmələrdədir.
Hydration makes server HTML interactive without rebuilding it. hydrateRoot(domNode, reactNode) renders your component tree in the browser as usual, but instead of creating DOM nodes it walks the nodes that are already in the document, claims them one by one in the same order and attaches the event handlers. When it finishes, the root behaves like any client-rendered root.
import { renderToPipeableStream } from "react-dom/server";
import { App } from "./App";
app.get("/products", (req, res) => {
const { pipe } = renderToPipeableStream(<App />, {
bootstrapScripts: ["/client.js"],
onShellReady() {
res.setHeader("Content-Type", "text/html");
pipe(res);
},
});
});import { hydrateRoot } from "react-dom/client";
import { App } from "./App";
hydrateRoot(document, <App />);Here App renders the whole <html> document, so the client hydrates document. The server sends HTML plus a <script> that loads client.js; the browser paints the HTML immediately and runs the script when it arrives.
It must produce the same tree
Hydration is not a "diff and patch" step. React assumes the first client render produces exactly the output the server produced, and react.dev asks you to treat every mismatch as a bug. Checking every attribute of every node would make hydration too slow for the common case where nothing differs, so React does not do it.
That means the first client render may only use what the server also had:
- the same components and the same props;
- the same data, which frameworks serialize into the page (a JSON script or the Server Components payload) so the client does not fetch it again;
- no browser-only inputs:
localStorage,window.matchMedia, the device's time zone, a random number.
What it costs
Hydration skips creating DOM nodes, not rendering. Every component on the page still has to be downloaded, parsed and run once on the . Until that work is done, the page looks ready but React's event handlers are not attached yet. This gap, and how to shrink it, is covered in the senior sections below.
Why hydration mismatches happen
Uyğunsuzluq o deməkdir ki, client-dəki ilk render server HTML-indən fərqli nəticə verib. React 19-un öz xəta mesajı tipik səbəbləri sadalayır və onların hamısı iki mühitdə fərqlənən dəyərlərdir:
- Server/client şaxələnməsi, məsələn
if (typeof window !== "undefined"). - Dəyişkən giriş:
Date.now(),new Date(),Math.random(). - Locale və saat qurşağına görə formatlama. Server adətən UTC-də və bir locale ilə işləyir, istifadəçinin brauzerinin isə öz ayarları var.
- Snapshot-u HTML ilə göndərilməyən xarici data: client daha təzə data gətirib və ya brauzer store-unu oxuyub.
- Yanlış HTML iç-içəliyi. Brauzerin HTML parser-i markup-u "düzəldir" və DOM React-in render etdiyi kimi olmur.
- Brauzer genişləndirmələri, React yüklənməmişdən əvvəl HTML-i dəyişənlər.
Klassik hal: render zamanı localStorage oxumaq
function useTemperatureUnit() {
const [unit, setUnit] = useState(() =>
typeof window === "undefined" ? "C" : (localStorage.getItem("unit") ?? "C"),
);
return [unit, setUnit];
}Bu yoxlama serverin çökməsinin qarşısını alır, amma ayarını saxlamış hər kəs üçün iki fərqli ilk render-i də təmin edir: server 21 °C render edir, Fahrenheit seçmiş istifadəçinin brauzeri isə 70 °F. Default ayarlı test hesabı bu bug-ı heç vaxt görmür; o, yalnız ayarlarını saxlamış istifadəçilərdə, səhifə hydrate olunanda üzə çıxır.
Saat qurşaqları və locale-lar
const placedAt = Date.UTC(2026, 10, 16, 22, 30);
new Date(placedAt).toLocaleDateString("en-US", { timeZone: "UTC" });
new Date(placedAt).toLocaleDateString("az-AZ", { timeZone: "Asia/Baku" });Birinci çağırış "11/16/2026", ikincisi "17.11.2026" qaytarır: Bakıda artıq növbəti gündür. Gecə saatlarında verilən sifarişlər yalnız bəzi saat qurşaqlarındakı istifadəçilər üçün səhv görünür, ona görə bu bug testlərdən asanlıqla keçir.
Yanlış iç-içəlik
<p>Total: <div>{price}</div></p> etibarsız HTML-dir. Parser <div>-dən əvvəl <p>-ni bağlayır, ona görə server HTML-indən qurulan DOM <p>Total: </p><div>…</div><p></p> olur və React render etmədiyi node-larla qarşılaşır. Development-də React xəbərdarlıq edir: "In HTML, <div> cannot be a descendant of <p>. This will cause a hydration error."
Sayğacla yaradılan id-lər
Modul səviyyəsindəki nextId++ uzun müddət işləyən serverdə və təzə açılmış brauzerdə fərqli id-lər verir. useId məhz bunun üçündür: id-ni komponentin ağacdakı mövqeyindən çıxarır, ağaclar eyni qaldıqca bu mövqe hər iki tərəfdə eynidir.
İnsident simulyatorundakı Hydration uyğunsuzluğu: səhifə yenidən qurulur insidentində hydration uyğunsuzluğunu production telemetriyasına əsasən araşdırmağı məşq edə bilərsən.
A mismatch means the first client render produced something different from the server HTML. React 19's own error message lists the usual suspects, and every one of them is a value that differs between the two environments:
- A server/client branch, such as
if (typeof window !== "undefined"). - Variable input:
Date.now(),new Date(),Math.random(). - Locale and time zone formatting. The server usually runs in UTC with one locale; the user's browser has its own.
- External data without a snapshot sent along with the HTML: the client fetched newer data, or read a browser store.
- Invalid HTML nesting. The browser's HTML parser repairs the markup, so the DOM is not what React rendered.
- Browser extensions that change the HTML before React loads.
The classic: reading localStorage during render
function useTemperatureUnit() {
const [unit, setUnit] = useState(() =>
typeof window === "undefined" ? "C" : (localStorage.getItem("unit") ?? "C"),
);
return [unit, setUnit];
}The guard keeps the server from crashing, but it also guarantees two different first renders for everyone who saved a preference: the server renders 21 °C, the browser of a user who chose Fahrenheit renders 70 °F. A test account with default settings never sees the bug; it appears only for users with saved settings, once the page hydrates.
Time zones and locales
const placedAt = Date.UTC(2026, 10, 16, 22, 30);
new Date(placedAt).toLocaleDateString("en-US", { timeZone: "UTC" });
new Date(placedAt).toLocaleDateString("az-AZ", { timeZone: "Asia/Baku" });The first call gives "11/16/2026", the second "17.11.2026": in Baku it is already the next day. Late-evening orders are only wrong for users in some time zones, which is why this bug survives testing.
Invalid nesting
<p>Total: <div>{price}</div></p> is invalid HTML. The parser closes the <p> before the <div>, so the DOM built from the server HTML is <p>Total: </p><div>…</div><p></p>, and React finds nodes it did not render. In development React warns: "In HTML, <div> cannot be a descendant of <p>. This will cause a hydration error."
Counters as ids
A module-level nextId++ gives different ids on a long-running server than in a fresh browser. useId exists for this: it derives the id from the component's position in the tree, which is the same on both sides as long as the trees match.
The Incident Simulator's Hydration mismatch: the page rebuilds itself incident lets you practise debugging a hydration mismatch from production telemetry.
What React 19 does on a mismatch
React mətn və ya element fərqləri ilə atribut fərqlərinə fərqli yanaşır. Cədvəl React 19.3-ün hər halda nə etdiyini göstərir (Chromium-da development və production build-ləri ilə yoxlanılıb):
| Fərq | Development | Production | Hydration-dan sonra DOM |
|---|---|---|---|
Mətn və ya element, ətrafında <Suspense> yoxdur | server/client diff-i ilə xəta | Minified React error #418 | bütün root yenidən yaradılır |
Eyni fərq, <Suspense> sərhədinin içində | eyni xəta | #418 | yalnız həmin sərhəd yenidən yaradılır |
Atribut (className, href, id) | konsolda xəbərdarlıq | heç nə | serverin dəyəri qalır |
suppressHydrationWarning olan elementin mətni | heç nə | heç nə | serverin mətni qalır |
Mətn və element uyğunsuzluqları
Məzmunu fərqlənən alt ağacı React hydrate edə bilmir. Ona görə server HTML-ini ən yaxın <Suspense> sərhədinə qədər (sərhəd yoxdursa, bütün root-u) atır və həmin hissəni client-də yenidən render edir. Development mesajı bunu açıq deyir: "Hydration failed because the server rendered text didn't match the client. As a result this tree will be regenerated on the client."
Səhifə işləməyə davam edir, amma bu bərpa baha başa gəlir və gözə görünür:
- yenidən yaradılan hər node yenidir, ona görə hydration bitməmiş input-a yazılan mətn itir, fokus da itir;
- render işi iki dəfə görülür, həm də onsuz da yüklənmə ilə məşğul olan səhifədə;
- yeni node-lar köhnələri əvəz edərkən məzmun yerindən oynaya bilər.
Atribut uyğunsuzluqları
Atributa görə React heç nəyi yenidən yaratmır. Development-də o yazır: "A tree hydrated but some attributes of the server rendered HTML didn't match the client properties. This won't be patched up." Production-da isə heç nə demir və DOM-da serverin dəyəri qalır. Yəni səhv href və ya aria-* atributu production-da heç kimin xəbəri olmadan qala bilər.
Xətaların ötürülməsi
Bu xətalar bərpa olunan xətalardır: React onları bildirir və işinə davam edir. Onları error tracker-ə göndər — production-da bug-ın görünən yeganə izi #418-dir.
hydrateRoot(document, <App />, {
onRecoverableError(error, errorInfo) {
reportToTracker(error, errorInfo.componentStack);
},
});Brauzer genişləndirmələri
React 19 üçüncü tərəf skriptlərinin və ya genişləndirmələrin <head> və <body>-yə əlavə etdiyi gözlənilməz teq-ləri uyğunsuzluq saymır, sadəcə ötüb keçir. Başqa bir uyğunsuzluğa görə bütün sənədi yenidən render etməli olsa belə, genişləndirmələrin əlavə etdiyi stil fayllarını yerində saxlayır. Komponentlərinin içindəki mətni dəyişən genişləndirmələr isə yenə uyğunsuzluq yarada bilər. Ona görə şübhəli xəta gələndə öz kodunda bug axtarmazdan əvvəl onu təmiz brauzer profilində yoxla.
React treats differences in text or elements and differences in attributes differently. The table shows what React 19.3 does in each case (checked in Chromium with the development and production builds):
| Difference | Development | Production | DOM after hydration |
|---|---|---|---|
Text or element, no <Suspense> around it | error with a server/client diff | Minified React error #418 | the whole root is re-created |
The same, inside a <Suspense> boundary | the same error | #418 | only that boundary is re-created |
An attribute (className, href, id) | console warning | nothing | the server's value stays |
Text inside an element with suppressHydrationWarning | nothing | nothing | the server's text stays |
Text and element mismatches
React cannot hydrate a subtree whose content differs, so it throws away the server HTML up to the nearest <Suspense> boundary (or the whole root when there is none) and renders that part again on the client. The development message says so: "Hydration failed because the server rendered text didn't match the client. As a result this tree will be regenerated on the client."
The page keeps working, but the recovery is expensive and visible:
- every regenerated node is new, so text typed into an input before hydration finished is gone and focus is lost;
- the render work is done twice, on a page that was already busy loading;
- content can jump while the new nodes replace the old ones.
Attribute mismatches
React does not regenerate anything for an attribute. In development it logs "A tree hydrated but some attributes of the server rendered HTML didn't match the client properties. This won't be patched up." In production it says nothing, and the DOM keeps the server's value. A wrong href or aria-* attribute can therefore live in production unnoticed.
Reporting
These errors are recoverable: React reports them and keeps going. Send them to your error tracker; in production, #418 is the only visible sign of the bug.
hydrateRoot(document, <App />, {
onRecoverableError(error, errorInfo) {
reportToTracker(error, errorInfo.componentStack);
},
});Browser extensions
React 19 skips unexpected tags in <head> and <body> that third-party scripts or extensions inserted, instead of treating them as a mismatch. If it has to re-render the whole document for an unrelated mismatch, it leaves stylesheets inserted by extensions in place. Extensions that change text inside your components can still cause mismatches, so check a suspicious report in a clean browser profile before you hunt for a bug in your code.
Fixing mismatches the right way
Bütün düzəlişlərin arxasında bir qayda dayanır: ilk client render yalnız serverin də bildiyi şeylərdən istifadə edə bilər. Yalnız brauzerdə olan dəyərlər ya hydration-dan sonra gəlir, ya da server onları öyrənməlidir.
1. Serverin dəyərini render et, sonra effektdə yenilə
Yuxarıdakı hook üçün:
function useTemperatureUnit() {
const [unit, setUnit] = useState("C");
useEffect(() => {
const saved = localStorage.getItem("unit");
if (saved) setUnit(saved);
}, []);
return [unit, setUnit];
}İlk render server HTML-i ilə üst-üstə düşür, React mövcud DOM-u saxlayır, effekt isə hydration-dan dərhal sonra yadda saxlanmış vahidi tətbiq edir. react.dev buna iki keçidli render deyir; qiyməti bir əlavə render və °C-dən °F-ə gözə görünən keçiddir.
2. getServerSnapshot ilə useSyncExternalStore
Brauzer store-unda yaşayan və sonradan dəyişə bilən dəyər üçün üçüncü arqumenti ötür. React getServerSnapshot-dan serverdə və hydration zamanı istifadə edir, dəyər fərqlidirsə, sonra getSnapshot ilə yenidən render edir:
const subscribe = (onChange) => {
window.addEventListener("storage", onChange);
return () => window.removeEventListener("storage", onChange);
};
function useSavedUnit() {
return useSyncExternalStore(
subscribe,
() => localStorage.getItem("unit") ?? "C",
() => "C",
);
}getServerSnapshot serverdə və ilk client render-də tam eyni dəyəri qaytarmalıdır. storage hadisəsi yalnız digər tab-larda baş verir, ona görə dəyəri bu tab-da yazan kod abunəçiləri özü xəbərdar etməlidir.
3. Serverə xəbər ver
Hər iki düzəliş JavaScript işləyənə qədər yenə °C göstərir. Əsl həll seçimi serverin oxuya biləcəyi yerdə saxlamaqdır: cookie-də və ya istifadəçi profilində. Server düzgün vahidi render edir, client eyni dəyəri prop kimi alır və hydration-dan sonra heç nə dəyişmir. Saat qurşağı və locale üçün də eyni qayda aiddir: hər mühitin öz default-u ilə yox, hər iki tərəfin aldığı açıq timeZone və locale ilə formatla.
4. suppressHydrationWarning — yalnız qaçılmaz mətn üçün
<time dateTime={iso} suppressHydrationWarning>
{new Date(iso).toLocaleTimeString()}
</time>O, yalnız həmin bir elementin mətni və atributları üçün xəbərdarlığı susdurur (bir səviyyə dərinliyində). Heç nəyi düzəltmir: React mətni yeniləmir, növbəti render-ə qədər ekranda serverin dəyəri qalır. Yadda saxlanmış ayar üçün bu, sadəcə xətanı gizlədərdi: istifadəçilər serverin dəyərini görməyə davam edərdi.
5. Yalnız client-də işləyən komponentlər
React 19.3 react-dom-a browser() əlavə edib. <Suspense> sərhədinin içindəki Client Component-də use(browser()) çağıranda server HTML-də fallback-i saxlayır, komponenti isə brauzer render edir. Bu, bərpa olunan xəta sayılmır; server onu onBrowserBailout vasitəsilə log edə bilər. Köhnə yanaşma — react.dev-in Suspense səhifəsində hələ də var — serverdə sərhədin içində xəta atmaqdır.
The rule behind every fix: the first client render may use only what the server also knew. Browser-only values come after hydration, or the server has to learn them.
1. Render the server's value, then update in an Effect
For the hook above:
function useTemperatureUnit() {
const [unit, setUnit] = useState("C");
useEffect(() => {
const saved = localStorage.getItem("unit");
if (saved) setUnit(saved);
}, []);
return [unit, setUnit];
}The first render matches the server HTML, React keeps the existing DOM, and the Effect applies the saved unit right after hydration. react.dev calls this two-pass rendering; its cost is one more render and a visible switch from °C to °F.
2. useSyncExternalStore with getServerSnapshot
For a value that lives in a browser store and can change later, pass a third argument. React uses getServerSnapshot on the server and during hydration, then re-renders with getSnapshot if the value differs:
const subscribe = (onChange) => {
window.addEventListener("storage", onChange);
return () => window.removeEventListener("storage", onChange);
};
function useSavedUnit() {
return useSyncExternalStore(
subscribe,
() => localStorage.getItem("unit") ?? "C",
() => "C",
);
}getServerSnapshot must return exactly the same value on the server and on the first client render. The storage event fires only in other tabs, so code that writes the value in this tab must notify the subscribers itself.
3. Let the server know
Both fixes still show °C until the JavaScript has run. The real fix is to keep the preference where the server can read it: a cookie or the user's profile. The server renders the right unit, the client gets the same value as a prop, and nothing changes after hydration. The same goes for time zones and locales: format with an explicit timeZone and locale that both sides receive, instead of each environment's default.
4. suppressHydrationWarning, only for unavoidable text
<time dateTime={iso} suppressHydrationWarning>
{new Date(iso).toLocaleTimeString()}
</time>It silences the warning for that one element's text and attributes (one level deep). It does not fix anything: React does not patch the text, so the server's value stays on screen until the next render. For a saved preference it would only hide the error: users would keep seeing the server's value.
5. Client-only components
React 19.3 adds browser() to react-dom. Calling use(browser()) in a Client Component inside a <Suspense> boundary makes the server leave the fallback in the HTML; the browser then renders the component. This is not a recoverable error; the server can log it through onBrowserBailout. The older pattern, still shown on react.dev's Suspense page, throws an error on the server inside a boundary.
Streaming and selective hydration
React 18-ə qədər server render üç baxımdan "ya hamısı, ya heç nə" idi: server nəsə göndərmək üçün hər şeyi gətirməli, client nəyisə hydrate etmək üçün bütün kodu yükləməli, istifadəçi isə nə iləsə işləmək üçün hər şeyin hydrate olunmasını gözləməli idi. Streaming və selective hydration bu üç gözləməni aradan qaldırır və hər ikisi <Suspense> üzərində qurulub.
HTML-in stream edilməsi
function ProductPage() {
return (
<Layout>
<ProductGrid />
<Suspense fallback={<ReviewsSkeleton />}>
<Reviews />
</Suspense>
</Layout>
);
}<Suspense> sərhədlərindən kənarda qalan hər şey shell-dir. Shell render olunan kimi renderToPipeableStream onShellReady-ni çağırır və sən pipe etməyə başlayırsan. HTML-də rəylərin yerində ReviewsSkeleton olur. Reviews data-nı alanda React onun HTML-ini fallback-i əvəz edən kiçik inline <script> ilə birlikdə eyni cavaba yazır — hələ brauzerdə React-in özü yüklənməmiş. Shell-i "minimal, amma tam" qur: səhifə boyu spinner yox, real layout-un skeleti.
Bilməli olduğun kompromislər:
- Stream başlayandan sonra status kodunu dəyişmək olmur. Shell-dəki xətalar
onShellError-a düşür (onda fallback səhifə göndər); sərhədin içindəki xətalaronError-a düşür, sərhədin fallback-i göndərilir və client həmin hissəni yenidən render etməyə çalışır. - Crawler-lər və statik generasiya
onAllReady-ni gözləyib tam HTML ala bilər. - Timeout-dan sonra
abort()çağıranda React qalan fallback-ləri göndərir və həmin hissələri client-də render edir.
Selective hydration
Hydration hər <Suspense> sərhədi üzrə ayrıca gedir. React shell-i və kodu ilə HTML-i artıq gəlmiş sərhədləri başqa yerdəki yavaş hissəni və ya lazy komponenti gözləmədən hydrate edə bilir. İstifadəçi hələ hydrate olunmamış sərhədin içinə klikləsə, React onun prioritetini qaldırır və əvvəlcə onu hydrate edir (React 18 arxitekturası haqqındakı yazıya görə, bunu klikin capture fazasında sinxron edir).
Sərhədlər uyğunsuzluğun zərərini də məhdudlaşdırır: React yalnız fərqin tapıldığı sərhədi yenidən yaradır, ondan kənardakı state və DOM salamat qalır. Yeganə sərhədi root olan səhifə isə bir səhv dəyərə görə hər şeyi itirir.
Amma sərhədlər pulsuz deyil: hər biri fallback-in görünə biləcəyi bir nöqtədir. Onları hər komponentin ətrafına yox, yavaş (data və ya kod) və ya müstəqil hissələrin (şərhlər, tövsiyələr, chat widget-i) ətrafına qoy.
Before React 18, server rendering was all-or-nothing in three ways: the server had to fetch everything before it could send anything, the client had to load all the code before it could hydrate anything, and it had to hydrate everything before the user could interact with anything. Streaming and selective hydration remove those three waits, and both are built on <Suspense>.
Streaming the HTML
function ProductPage() {
return (
<Layout>
<ProductGrid />
<Suspense fallback={<ReviewsSkeleton />}>
<Reviews />
</Suspense>
</Layout>
);
}Everything outside <Suspense> boundaries is the shell. renderToPipeableStream calls onShellReady as soon as the shell is rendered, and you start piping. The HTML contains ReviewsSkeleton in place of the reviews. When Reviews has its data, React writes its HTML into the same response together with a small inline <script> that swaps out the fallback, before React itself has loaded in the browser. Design the shell to be "minimal but complete": a skeleton of the real layout, not a page-wide spinner.
Trade-offs to know:
- Once you have started streaming, you can no longer change the status code. Errors inside the shell are reported to
onShellError(send a fallback page); errors inside a boundary are reported toonError, the boundary's fallback is sent, and the client retries rendering that part. - Crawlers and static generation can wait for
onAllReadyand receive the complete HTML. abort()after a timeout makes React send the remaining fallbacks and render those parts on the client.
Selective hydration
Hydration happens per <Suspense> boundary. React can hydrate the shell and the boundaries whose code and HTML have arrived without waiting for a slow chunk or a lazy component elsewhere. If the user clicks inside a boundary that is not hydrated yet, React raises its priority and hydrates it first (the React 18 architecture write-up says it does so synchronously during the click's capture phase).
Boundaries also limit the damage of a mismatch: React re-creates only the boundary in which the difference was found, so state and DOM outside it survive. A page whose only boundary is the root loses everything on a single wrong value.
Boundaries are not free, though: each one is a point where a fallback can appear. Put them around parts that are slow (data or code) or independent (comments, recommendations, a chat widget), not around every component.
The interactivity gap and the cost of hydration
Server HTML-i React işləməzdən əvvəl çəkilir, ona görə bir müddət səhifə hazır görünür, amma React event handler-lərini hələ bağlamayıb. web.dev bunu belə təsvir edir: server-də render olunmuş səhifələr yüklənmiş və interaktiv görünə bilər, amma client skriptləri işləyənə qədər input-a cavab verə bilmir. Bu boşluğu çox vaxt uncanny valley adlandırırlar. Sürətli noutbukda o millisaniyələr çəkir, böyük bundle-ı olan orta səviyyəli telefonda isə saniyələrlə uzana bilər.
İstifadəçi nə görür
- Davranışı React
onClick-i olan düymələr heç nə etmir. Adi link-lər və form-lar isə işləyir, çünki onları brauzer özü idarə edir. - Input-lar yazını qəbul edir, çünki onlar adi HTML elementləridir. Uyğunsuzluğa görə hydration sonra həmin ağacı yenidən yaratsa, yazılan mətn itir.
- Uzun hydration tapşırığının ortasına düşən kliklər onun bitməsini gözləyir. Bu gecikmə INP-yə daxil olur, yüklənmə zamanı uzun tapşırıqlar TBT-də görünür, LCP isə əla qalır. Yalnız LCP-yə baxan dashboard problemi görməyəcək.
Niyə bu qədər baha başa gəlir
Hydration client ağacının ölçüsünə mütənasib işidir: hər komponenti yüklə, təhlil et, icra et, sonra listener-ləri bağla. Data-nın haqqı da çox vaxt iki dəfə ödənir: bir dəfə HTML kimi, bir dəfə də client render üçün serializasiya olunmuş JSON kimi.
Boşluğu kiçiltmək
- Hydrate olunacaq kodu azalt. Server Components ilə (məsələn, Next.js App Router-də) brauzer üçün yalnız
'use client'ilə işarələnmiş modullar və onların import etdikləri bundle-a düşür. Server Component-lər kodlarını yox, render nəticələrini göndərir və hydrate olunmur. Client Component-lər isə yenə serverdə HTML-ə render olunur və hydrate edilir.'use client'-i bütöv layout-lara yox, interaktiv yarpaqlara (axtarış qutusu, like düyməsi) qədər endir. <Suspense>ilə böl ki, vacib hissələr əvvəl hydrate olunsun və qalanları onları bloklamasın.- Ekranın aşağısındakı widget-ləri və üçüncü tərəf skriptlərini lazy yüklə.
- Render-i ucuz saxla: hydration zamanı işləyən komponentlərdə ağır hesablama olmasın.
- JavaScript olmadan da işləsin: əsl
<a href>və<form action>elementləri hydration-dan əvvəl də nəsə edir.
Təxmin etmə, ölç: Performance panelində CPU throttling ilə səhifənin yüklənməsini yaz, HTML çəkiləndən sonrakı uzun hydration tapşırığını tap və real istifadəçilərdən INP-ni izlə.
Server HTML is painted before React runs, so for a while the page looks ready but React has not attached its event handlers yet. web.dev describes it this way: server-rendered pages can appear loaded and interactive but cannot respond to input until the client scripts have run. The gap is often called the uncanny valley. On a fast laptop it lasts milliseconds; on a mid-range phone with a large bundle it can last seconds.
What the user experiences
- Buttons whose behaviour is a React
onClickdo nothing. Real links and forms still work, because the browser handles them natively. - Inputs accept typing, because they are plain HTML elements. If hydration later regenerates that tree after a mismatch, the typed text is lost.
- Clicks that land during a long hydration task wait until it finishes. That delay counts towards INP, and long tasks during load show up in TBT, while LCP looks great. A dashboard that only watches LCP will not see the problem.
Why it costs so much
Hydration is work proportional to the size of the client tree: download, parse and run every component, then attach the listeners. The data is often paid for twice, once as HTML and once as serialized JSON for the client render.
Shrinking the gap
- Ship less code to hydrate. With Server Components (for example the Next.js App Router), only modules marked
'use client'and what they import are bundled for the browser. Server Components send their rendered output, not their code, and are not hydrated. Client Components are still rendered to HTML on the server and hydrated. Push'use client'down to the interactive leaves (a search box, a like button), not to whole layouts. - Split with
<Suspense>so the important parts hydrate first and the rest does not block them. - Lazy-load below-the-fold widgets and third-party scripts.
- Keep render cheap: no heavy computation in components that run during hydration.
- Degrade gracefully: real
<a href>and<form action>elements still do something before hydration.
Measure it rather than guess: record a page load with CPU throttling in the Performance panel, look for the long hydration task after the HTML is painted, and track INP from real users.
Interview tips
30 saniyəlik cavab. "SSR HTML-i serverdə render edir ki, məzmun JavaScript işləməzdən əvvəl görünsün. Sonra hydration eyni komponentləri brauzerdə icra edir, mövcud DOM-u mənimsəyir və event handler-ləri bağlayır. O, ilk client render-in server HTML-i ilə tam üst-üstə düşdüyünü fərz edir. Mətn fərqlənsə, React ağacın həmin hissəsini ən yaxın Suspense sərhədinə qədər yenidən yaradır; atributlar fərqlənsə, serverin dəyərlərini saxlayır."
Gözlənilən suallar
- CSR, SSR, SSG, streaming — hansını seçərdin? Onları TTFB, FCP/LCP, INP, təzəlik və xərc baxımından müqayisə et, sonra hər route üçün seç: statik marketinq səhifələri, streaming məhsul səhifələri, client-də render olunan redaktor.
- Hydration uyğunsuzluqlarına nə səbəb olur?
typeof windowşaxələri, tarixlər və saat qurşaqları,Math.random(), render zamanılocalStoragevə yamatchMediaoxumaq, yanlış iç-içəlik, genişləndirmələr. Hər birinin iki render-i niyə fərqləndirdiyini izah et. - Onu necə düzəldirsən? Əvvəlcə serverin dəyərini render et, sonra effektdə yenilə;
getServerSnapshotiləuseSyncExternalStoreistifadə et; ən yaxşısı dəyəri serverə məlum et (cookie).suppressHydrationWarningyalnız timestamp kimi qaçılmaz mətn üçündür. - Streaming və selective hydration nəyi həll edir? Üç gözləməni: hər şeyi gətir, hər şeyi yüklə, hər şeyi hydrate et. Shell-i, fallback-ləri əvəz edən inline skriptləri və prioritetə görə hydration-u qeyd et.
- Səhifə görünür, amma niyə reaksiya vermir? İnteraktivlik boşluğu: HTML çəkilib, handler-lər hələ bağlanmayıb. Bunu INP və bundle ölçüsü ilə əlaqələndir.
Bal itirdən səhvlər
- Hydration-un "səhifəni DOM-a yenidən render etdiyini" demək. O, komponentləri yenidən render edir, amma serverin node-larını təkrar istifadə edir.
suppressHydrationWarning-i düzəliş adlandırmaq. O, xəbərdarlığı gizlədir; səhv mətn yerində qalır.- React-in hər fərqi düzəltdiyini demək. Atributlar düzəldilmir; mətn və elementlər isə yerində düzəldilmir, yenidən yaradılır.
- SSR-in daha az JavaScript demək olduğunu söyləmək. Server Components olmadan hydration üçün eyni kod yenə göndərilir.
Senior səviyyəni göstərən məqamlar
Əməliyyat tərəfindən danış: onRecoverableError-u komponent stack-i ilə hər reliz üzrə izlə, hydration-u yadda saxlanmış ayarlarla, başqa saat qurşaqlarında və locale-larda test et, render kodunda typeof window, Date və localStorage-i code review-da risk siqnalı say. Uyğunsuzluqların harada göründüyünü də bil: xəta sayında və itən input-da, LCP kimi yüklənmə metrikalarında isə nadir hallarda.
A 30-second answer. "SSR renders HTML on the server so content appears before JavaScript runs. Hydration then runs the same components in the browser, claims the existing DOM and attaches event handlers. It assumes the first client render matches the server HTML exactly. If text differs, React re-creates that part of the tree up to the nearest Suspense boundary; if attributes differ, it keeps the server's values."
Questions you are likely to get
- CSR vs SSR vs SSG vs streaming: which would you choose? Compare them on TTFB, FCP/LCP, INP, freshness and cost, then choose per route: static marketing pages, streamed product pages, a client-rendered editor.
- What causes hydration mismatches?
typeof windowbranches, dates and time zones,Math.random(), readinglocalStorageormatchMediaduring render, invalid nesting, extensions. Explain why each one makes the two renders differ. - How do you fix one? Render the server's value first and update in an Effect; use
useSyncExternalStorewithgetServerSnapshot; better still, make the value known to the server (a cookie). UsesuppressHydrationWarningonly for unavoidable text such as a timestamp. - What do streaming and selective hydration solve? The three waits: fetch everything, load everything, hydrate everything. Mention the shell, the inline scripts that swap fallbacks, and hydration in priority order.
- Why is the page visible but unresponsive? The interactivity gap: HTML is painted, handlers are not attached yet. Tie it to INP and to bundle size.
Mistakes that cost points
- Saying hydration "renders the page again into the DOM". It renders the components again but reuses the server's nodes.
- Calling
suppressHydrationWarninga fix. It hides the warning; the wrong text stays. - Saying React patches every difference. Attributes are not patched; text and elements are re-created, not fixed in place.
- Saying SSR means less JavaScript. Without Server Components the same code still ships to hydrate.
Senior signal
Talk about operations: report onRecoverableError with the component stack per release, test hydration with saved preferences and in other time zones and locales, and treat typeof window, Date and localStorage in render code as review red flags. And know where mismatches show up: in error rates and lost input, rarely in load metrics such as LCP.
What to check when reviewing SSR and hydration code
Yazmadığın, serverdə render olunan komponentləri — komanda yoldaşının, kitabxananın və ya AI assistentin kodunu — review edəndə bu siyahıdan istifadə et. client-dəki ilk render-in server HTML-i ilə tam üst-üstə düşəcəyini gözləyir; düşməsə, React səhifənin bir hissəsini yenidən yaradır, yazılmış mətn və fokus itir, səhv atributlar isə production-da heç kimin xəbəri olmadan qalır.
- İlk render yalnız brauzerdə olan dəyərləri oxuyurmu? Render-də və ya
useStateinitializer-indətypeof windowşaxələri,localStoragevə yawindow.matchMediaonu serverin render-indən fərqli edir, default ayarlı test hesabı isə bunu heç vaxt göstərmir. Serverin dəyərini render et və effektdə yenilə,getServerSnapshotiləuseSyncExternalStoreistifadə et və ya dəyəri serverin oxuduğu cookie-də saxla. - Tarixlər və təsadüfi dəyərlər hər iki tərəfdə eynidirmi?
new Date(),Date.now(),Math.random()və açıqtimeZonevə locale verilmədən çağırılantoLocaleDateString()serverdə və brauzerdə fərqli mətn verir. Səhifəni başqa saat qurşağında və başqa locale ilə yoxla. suppressHydrationWarningyalnız timestamp kimi qaçılmaz mətn üçün işlədilirmi? O, xəbərdarlığı bir səviyyə dərinliyində susdurur və heç nəyi düzəltmir: növbəti render-ə qədər ekranda serverin mətni qalır.- HTML iç-içəliyi düzgündürmü, id-lər
useIdilə yaradılırmı?<p>Total: <div>…</div></p>-də parser<p>-ni vaxtından əvvəl bağlayır, ona görə DOM React-in render etdiyi kimi olmur; modul səviyyəsindəkinextId++isə uzun müddət işləyən serverdə və təzə açılmış brauzerdə fərqli id-lər verir. hydrateRoot-a xətaları error tracker-ə göndərənonRecoverableErrorverilibmi? Production-da mətn uyğunsuzluğu yalnızMinified React error #418kimi görünür, atribut uyğunsuzluğu isə heç görünmür.- Yavaş və ya müstəqil hissələrin öz
<Suspense>sərhədi varmı? Onda uyğunsuzluq bütün root-u yox, yalnız həmin sərhədi yenidən yaradır, səhifənin qalanı isə onu gözləmədən hydrate olunur.
Use this list when you review server-rendered components you did not write: a teammate's, a library's or an AI assistant's. expects the first client render to match the server HTML exactly; otherwise React re-creates part of the page, losing typed input and focus, and wrong attributes stay unnoticed in production.
- Does the first render read browser-only values?
typeof windowbranches,localStorageorwindow.matchMediain render or auseStateinitializer make it differ from the server's, and a test account with default settings never shows it. Render the server's value and update in an Effect, useuseSyncExternalStorewithgetServerSnapshot, or keep the value in a cookie the server reads. - Are dates and random values the same on both sides?
new Date(),Date.now(),Math.random()andtoLocaleDateString()without an explicittimeZoneand locale give the server and the browser different text. Test the page in another time zone and locale. - Is
suppressHydrationWarningkept for unavoidable text such as a timestamp? It silences the warning one level deep and fixes nothing: the server's text stays until the next render. - Is the HTML nesting valid, and are ids made with
useId? In<p>Total: <div>…</div></p>the parser closes the<p>early, so the DOM is not what React rendered; a module-levelnextId++gives different ids on a long-running server and in a fresh browser. - Does
hydrateRootget anonRecoverableErrorthat reports to the error tracker? In production a text mismatch shows only asMinified React error #418, and an attribute mismatch shows nothing. - Are slow or independent parts in their own
<Suspense>boundary? A mismatch then re-creates only that boundary, not the whole root, and the rest of the page hydrates without waiting for it.
Check your understanding
Practise this
Hands-on work that uses this topic.