Angular 16 introduces non-destructive hydration, revolutionizing Angular SSR with awaited improvements.
The Angular team prioritizes enhancing Server Side Rendering in 2023, aiming to improve Core Web Vitals scores, SEO performance, and eliminate 'flicker' in Angular Universal applications. They consider non-destructive hydration as a crucial step towards their future vision.
Issue with classic SSR (Destructive Hydration)
If you’ve ever used an Angular Universal application you may have come across the ‘flicker’:
Angular Universal’s ‘flicker’ effect when using destructive hydration
This flicker occurs because Angular Universal uses destructive hydration by default. When an Angular application is Server Side Rendered, a static HTML file is immediately sent to the client on page load. This provides a faster First Contentful Paint than traditional SPAs because template is displayed before application code is downloaded.
With destructive hydration, as soon as the client code is bootstrapped it blows away the server-rendered DOM and replaces it with client-rendered DOM. That’s what causes the flicker.
Non-Destructive Hydration
This technique will allow us to reuse the server-side rendered DOM and rather than rerendering it only attach event listeners and create data structures required by the Angular runtime.
How do you enable hydration in Angular
Once you have SSR working with your application, you can enable hydration by visiting your main app component or module and importing provideClientHydration from @angular/platform-browser. You'll then add that provider to your app's bootstrapping providers list.
import {
bootstrapApplication,
provideClientHydration,
} from '@angular/platform-browser';
...
bootstrapApplication(RootCmp, {
providers: [provideClientHydration()]
});
Alternatively if you are using NgModules, you would add provideClientHydration to your root app module's provider list.
import {provideClientHydration} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
@NgModule({
declarations: [RootCmp],
exports: [RootCmp],
bootstrap: [RootCmp],
providers: [provideClientHydration()],
})
export class AppModule {}
New non-destructive hydration's impressive results: Lighthouse metrics of example application shown in two figures.
Top comments (0)