NashTech Insights

Table of Contents

Developer preview access is available to the hydration feature. It might change before it’s stable, but this blog has information about humidity.

What is Hydration?

Hydration is the cycle that reestablishes the server-side delivered application on the client. This includes transferring application data that was already retrieved by the server, reusing the server-rendered DOM structures, persisting the application state, and other processes.

Simply put, this procedure restores a client-side rendered application from the server. It boosts performance by avoiding the need to re-create DOM nodes.

When Angular Hydration is turned on, the client-side Angular application tries to match the existing DOM elements to the application structure at runtime rather than destroying and re-rendering the DOM. It can reduce UI flicker and boost performance by reusing these existing DOM elements.

Let’s say, for instance, that the blog posts’ server-generated HTML structure looks like this:

<div>
   <h1>Blog Title</h1>
   <ul>
     <li>Post 1</li>
     <li>Post 2</li>
     <li>Post 3</li>
   </ul>
 </div>

At the point when Precise Hydration is empowered, the client-side angular application would perceive the current DOM structure, coordinate it with the application’s construction, and reuse the DOM hubs as opposed to reproducing them. Subsequently, the client wouldn’t see a UI glimmer, and the presentation of the application would be gotten to the next level.

If you want to learn one more feature of angular, you can refer here.

Why is hydration important?

By avoiding the additional work of re-creating DOM nodes, hydration boosts application performance. Angular, on the other hand, reuses DOM nodes whenever possible and tries to match existing DOM elements to the application’s structure at runtime. This outcome in a presentation improvement that can be estimated utilizing Center Web Vitals (CWV) measurements, like lessening the Main Information Postponement (FID) and Biggest Contentful Paint (LCP), as well as Combined Format Shift (CLS). Things like SEO performance are also affected by raising these numbers.

Server-side rendered Angular applications will destroy and re-render the application’s DOM without hydration enabled, which may cause a visible UI flicker. This re-rendering may alter the layout and have a negative impact on Core Web Vitals like LCP. Empowering hydration permits the current DOM to be re-utilized and forestalls a glimmer

How to enable Angular hydration

To empower it, you want to import provideClientHydration from @angular/stage program and add it to your application’s bootstrapping suppliers list or your root application module’s supplier list.

An example of using a root app module to enable Angular Hydration is as follows:

import {provideClientHydration} from '@angular/platform-browser';
import {NgModule} from '@angular/core';

@NgModule({
declarations: [RootCmp],
exports: [RootCmp],
bootstrap: [RootCmp],
providers: [provideClientHydration()],
})
export class AppModule {}

Keep in mind that Angular Hydration imposes some constraints on your application, such as having the same DOM structure on both the server and client. Direct DOM manipulation should be avoided, as it may lead to errors during the hydration process. If necessary, you can use the ngSkipHydration attribute to skip hydration for particular components that do not work well with it.

How do you use Angular hydration?

To use it in your application, follow these steps:

Set up server-side rendering (SSR): Before enabling hydration, make sure your application uses Angular Universal for server-side rendering. If you haven’t set up SSR yet, follow the Angular Universal Guide.

Import provideClientHydration: Go to your main app component or module and import provideClientHydration from @angular/platform-browser.

Add provideClientHydration to providers list: Depending on your app’s structure, add provideClientHydration to the providers list either in the bootstrapping provider’s list or the root app module’s provider list.

For bootstrapping providers list, use the following code:

import {
 bootstrapApplication,
 provideClientHydration,
 } from '@angular/platform-browser';
 …
 ​
 bootstrapApplication(RootCmp, {
 providers: [provideClientHydration()]
 });

For the root app module’s provider list, use the following code:

import {provideClientHydration} from '@angular/platform-browser';
 import {NgModule} from '@angular/core';
 ​
 @NgModule({
 declarations: [RootCmp],
 exports: [RootCmp],
 bootstrap: [RootCmp],
 providers: [provideClientHydration()],
 })
 export class AppModule {}

Include provideClientHydration() in server bootstrap configuration: Ensure that the provideClientHydration() the call is included in the provider’s list used to bootstrap the application on the server. For applications with the default project structure generated by the ng new command, adding the call to the root AppModule should be sufficient. If you use a custom setup, add the provideClientHydration() call to the provider’s list in the server bootstrap configuration.

How to skip hydration for specific components

To skip hydration for specific components, you can use the ngSkipHydration attribute. Here are two ways to apply it:

Add ngSkipHydration attribute to the component’s tag: In your component’s template, add the ngSkipHydration attribute to the component’s tag like this:

<example-cmp ngSkipHydration />

Set ngSkipHydration as a host binding: In your component’s TypeScript file, add ngSkipHydration as a host binding within the @Component decorator:

@Component({
   ...
   host: {ngSkipHydration: 'true'},
 })
 class ExampleCmp {}

The ngSkipHydration attribute forces Angular to skip hydrating the entire component and its children. As a result, the component will behave as if hydration is not enabled, meaning it will destroy and re-render itself.

You might want to skip hydration for specific components in certain cases:

Direct DOM manipulation: If a component directly manipulates the DOM using native DOM APIs, it can cause hydration errors. Skipping hydration for that component can be a temporary workaround until the component is refactored to use Angular constructs.

Third-party libraries: Some third-party libraries, like D3 charts, rely on DOM manipulation and might cause DOM mismatch errors when hydration is enabled. You can skip hydration for components that use such libraries to avoid errors.

Common errors when using Angular hydration

Here are some common errors related to Angular Hydration:

  1. DOM mismatch errors:
    These errors occur when there’s a mismatch between the server-rendered DOM structure and the client-side DOM structure. They often happen due to direct DOM manipulation using native APIs, which results in hydration being unable to match the expected DOM tree structure.
  2. Invalid HTML structure:
    These errors occur when there’s a mismatch between the server-rendered DOM structure and the client-side DOM structure. They often happen due to direct DOM manipulation using native APIs, which results in hydration being unable to match the expected DOM tree structure.
  3. Inconsistent preserveWhitespaces configuration:
    If the preserveWhitespaces the setting is inconsistent between tsconfig.server.json and tsconfig.app.json, it can cause hydration issues. Make sure to use the same value for preserveWhitespaces in both configurations.
  4. Using ngSkipHydration incorrectly:
    If the ngSkipHydration the attribute is added to nodes other than component host nodes, Angular throws an error. Make sure to use the attribute only on component host nodes.
  5. Custom or Noop Zone.js implementations:
    Using custom or “noop” Zone.js implementations can lead to issues with serialization or cleanup during the this process. This is because the timing of the “stable” event may be different, causing hydration to break. Adjusting the timing of the onStable event in the custom Zone.js implementation may be necessary.

Conclusion:

By enabling Angular Hydration in your Angular application, you can significantly improve its performance by reusing server-rendered DOM nodes and minimizing UI flicker.

However, to take full advantage of this feature, you need to follow certain constraints, avoid direct DOM manipulation, and ensure your server-rendered HTML has a consistent structure with your client-side application. By doing so, you can avoid common errors and ensure your Angular application is performing at its best.

Finally, for more such posts, please follow our LinkedIn page- FrontEnd Competency.

Alka Vats

Alka Vats

Alka Vats is a Software Consultant at Nashtech. She is passionate about web development. She is recognized as a good team player, a dedicated and responsible professional, and a technology enthusiast. She is a quick learner & curious to learn new technologies. Her hobbies include reading books, watching movies, and traveling.

Leave a Comment

Your email address will not be published. Required fields are marked *

Suggested Article

%d bloggers like this: