在 Next.js 中,SSR 用於生成初始 HTML 頁面,該頁面包含已呈現的 React 组件。這使得頁面加載速度更快,並且在初始加載時可以提供良好的用戶體驗。但是,初始 HTML 頁面是靜態的,並且不包含任何交互性。
這就是 Hydration 進入的地方。Hydration 是指使用 JavaScript 將伺服器端渲染的 HTML 內容轉換為可互動的 DOM 元素。這包括將事件處理程序附加到元素、設置狀態以及使頁面栩栩如生。
Hydration 是 Next.js 的關鍵部分,因為它使您可以獲得 SSR 的優勢(快速初始頁面加載)以及客戶端渲染 (CSR) 的優勢(可互動性)。
Next.js's server-side rendering (SSR) delivers fast initial page loads, but it comes with a trade-off: the rendered pages lack interactivity. That's where hydration steps in.
Hydration is the process of breathing life into static HTML pages by transforming them into interactive DOM elements using JavaScript.
Why Hydration Matters
Hydration bridges the gap between SSR's speed and client-side rendering's (CSR) interactivity, providing the best of both worlds.