Incremental Hydration Mechanism Simplified
Hooman Pouyanasab
Senior Frontend Engineer | Team Lead | Angular Lead Developer | Crafting High-Impact, Scalable and Innovative Frontend Solutions | MEAN & MERN Stacks
?? First, let’s ask the main question: What makes a website slow?
?
?? Correct, JavaScript.
?
?? Long story short, it’s always been about the downloading and transmission of the JavaScript bundles that contribute to less performance in a web app, and incremental hydration was going to be a solution to this problem but we faced couple of issues, this is a story of the better solution.
?
??♀? It’s like when your mom says you can drink a huge bottle of orange juice ?? BUT you are allowed to only drink it in small sips ?? and intervals, not all at once.
?
?? Let’s say that you are the website (the building blocks of the website—components), orange juice is JavaScript, and your mom is the framework (not the best example but still :)). The whole process is called incremental hydration.
???? in this article i'm going to make things simple to understand under the hood so you will be more confident and skillful using this in SSR
?? JUST TO BE CLEAR ?? hydration only happens when your application is equipped with server side rendering (SSR) because it's all about re-using the DOM rendered on the server to attach event listeners, restore state and make the raw DOM and HTML document of you app interactive. with no ssr there will be no DOM to re-use and hydrate
?? Unpacking Incremental Hydration: Sipping JavaScript Responsibly
?
??? So, what exactly is incremental hydration, and why should we care?
?
?? Imagine visiting a website, and everything appears almost instantly ??. The text is there, the images are loaded, but when you try to click a button, nothing happens for a moment. Frustrating, right? ?? This delay occurs because, although the HTML and CSS have loaded, the JavaScript that makes the page interactive is still chugging along in the background.
?
?? hydration: is a technique that forces your browser to gulp down all the JavaScript in one go and hydrate the entire app (all component in the rendered) and make all sections of the page interactive by downloading their js (which can be overwhelming and slow)
????Incremental hydration is a technique designed to tackle this issue. Instead of forcing your browser to gulp down all the JavaScript in one go, it allows the browser to take in smaller, manageable sips of JavaScript, activating interactivity incrementally. (small sips of orange juice )
?
?? Why hydration could be considered pure overhead ?
?? it's simple
???? Although we're re-using the html DOM rendered on the server but it's not the expensive part in terms of performance, but it's the javascript bundles. so we're repeating ourselves by going through the js files twice, once in the server to render the page and build up the App State and once when we receive it in client's browser and intend to hydrate it with the js bundles
so even if we completely exclude hydration from the ssr process we would still be losing nothing that scary because javascript is the resource-intensive part
that's why it could be considered a pure overhead
?? BUT
?? with the incremental hydration, not the entire apps js would be unpacked entirely all at once and it offers Selective Interactivity
?? so it's a progress
??♀? The Problem It Solves: Bridging the Gap Between Speed and Interactivity
?? Now, you might be wondering, why can’t we just load all the JavaScript upfront and be done with it?
?? Well, as websites become more complex, the amount of JavaScript needed increases. Loading large JavaScript bundles can lead to longer load times and sluggish performance, especially on mobile devices or slower networks ??.
Incremental hydration addresses this by:
?? Reducing Initial Load Times: Only essential JavaScript needed for immediate interactivity is loaded upfront.
?? Enhancing User Experience: Users can start interacting with the critical parts of the website sooner.
?? Optimizing Resource Usage: Less strain on the browser and device, leading to smoother performance.
?? So Hydration improves application performance by avoiding extra work to re-create DOM nodes. Instead, Angular tries to match existing DOM elements to the applications structure at runtime and reuses DOM nodes when possible WHICH RESULTS IN reducing the First Input Delay (FID) and Largest Contentful Paint (LCP), as well as Cumulative Layout Shift (CLS) WHICH RESULTS IN improving SEO performance.
?? Starting from Angular 19 we will be able to use incremental hydration feature along with the AMAZING deferrable views (my favourite part) meaning that By leveraging deferrable views, or defer blocks (lazy load a component), developers can control when and how different parts of the application become interactive (hydrated). This approach allows content to be incrementally hydrated based on user actions, visibility, or specific conditions, such as hydrate on, hydrate when, or hydrate never. ?
?? How to setup incremental hydration in angular 19:
App.config.ts:
export const appConfig: ApplicationConfig = {
providers: [
provideClientHydration(withPartialHydration())
]
};
???? let's see some examples:
@defer (on viewport; hydrate on interaction) {
<deferred-user-projects />
<deferred-user-blogs />
}
?? *this component will be loaded and shown to the user ONLY when appears in the client's browser viewport on scroll AND will be hydrated ONLY when the clients starts interacting with the component (it means not only we are lazy loading the component but also not downloading it's javascript until user actually needs it)
???it's also possible to do hydration with nested components
@defer (hydrate on hover) {
@defer (hydrate on timer(15s)) {
...
}
}
?? *When multiple @defer blocks are in a dehydrated state, their conditions are evaluated concurrently.
? But you might ask yourself?, if the html is shown to the client as soon as its rendered on the server but the user doesn't know its not fully hydrated and might start interacting with it as soon as they see it on screen but there will be no javascript event listeners to reflect the action WHAT DO WE DO ? IS HYDRATION A PIECE OF SHIT ??!!
?? in angular 19 there is a concept called Event Replay Feature, this feature accumulates all the user interactions before incremental hydration of the related component and replay them once the component is hydrated and has javascript, its nice is it not ?
?? here is how to set up Event Replay Feature in hydration:
import {provideClientHydration, withEventReplay} from '@angular/platform-browser';
...
bootstrapApplication(App, {
providers: [
provideClientHydration(withEventReplay())
]
});
?? Also it's possible to completely disable hydration on some components and there are 2 ways to make that happen
First Approach:
<app-example ngSkipHydration />
-------------------------
Second Approach:
@Component({
...
host: {ngSkipHydration: 'true'},
})
class UserProjectsComponent {}
领英推荐
?? A Brief History: The Evolution of Hydration Techniques
?? Did you know that the concept of hydration has been around for quite some time?
?? Early Days: Websites were mostly static, and interactivity was minimal.
?? Rise of SPAs: Single Page Applications loaded everything upfront, leading to performance issues.
?? Introduction of SSR: To combat slow initial loads, SSR made a comeback.
?? Hydration Emerges: Developers needed a way to make SSR pages interactive without reloading everything—enter hydration.
??? Incremental Hydration: As applications grew, even hydration became heavy, leading to the incremental approach we see today.
??React & Astro have been pioneering in this area with features like Suspense and React.lazy and concept of ilands in astro
??? Astro
Astro is a modern framework built around the concept of partial hydration.
? Islands Architecture: Astro renders most of the page as static HTML and hydrates only the interactive parts when necessary
? Directives for Hydration: Use directives like client:visible to control hydration.
? Example:
?
<!-- Static Component with no js -->
<MyReactComponent />
<!-- This component is now interactive on the page! and has js -->
<MyReactComponent client:load />
React
? Streaming SSR: React 18 introduced streaming server-side rendering, allowing for components to be streamed and hydrated incrementally.
? Selective Hydration: Only hydrate components when they’re needed.
?? ? Example:
const LazyComponent = React.lazy(() => import('./LazyComponent'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
);
}
??? Under the Hood: How Does Incremental Hydration Work??
Let’s dive a bit deeper into how incremental hydration is implemented under the hood. Don’t worry; I’ll keep it as simple and clear as possible.
?
1. Server-Side Rendering (SSR) as the Foundation
The process begins with SSR, where the server generates the complete HTML for the page.
? Why SSR? Because it allows the user to see the fully rendered page quickly, without waiting for JavaScript to load.
?
2. Hydration: Bringing Interactivity to Static Content
Hydration is the process where the static HTML sent from the server is “brought to life” on the client side by attaching event listeners and JavaScript logic.
? Traditional Hydration: The entire page is hydrated in one go.
? Incremental Hydration: Only specific components are hydrated when needed.
?
3. Breaking It Down: The Incremental Approach
Here’s how incremental hydration manages to be efficient:
? Component-Level Hydration: The page is divided into components, each responsible for a part of the UI.
? Event-Driven Activation: Components hydrate in response to user actions or when they enter the viewport.
? Lazy Loading JavaScript: JavaScript code for each component is loaded only when necessary.
?
? Isn’t it exciting to be part of this evolving landscape?
By embracing these techniques, we not only improve our own skills but also contribute to a better web for everyone.
?
?? Final Thoughts
As we continue to push the boundaries of what’s possible on the web, performance and user experience remain at the forefront. Incremental hydration is more than just a buzzword—it’s a practical solution to real-world problems.
?
???? So next time you’re building a web app, consider taking those small sips of orange juice. Your users (and their devices) will thank you.
?
?? References and Further Reading
?
?
Feel free to dive deeper into the resources above, and happy coding!
Angular Developer @Simplyphi | IIT Indore Alumnus
5 个月Great explanation of Angular 19’s updates. Incremental hydration sounds like a huge improvement for making apps faster. I'm looking forward to more insights from you.