73

What the hell are hydration and rehydration ?

The rise of Single Page Application The Single Page Application (SPA) model has been very…

The rise of Single Page Application

The Single Page Application (SPA) model has been very popular over the past few years. It’s supposed to bring more speed, better experience, new patterns.

In fact a SPA works inside the browser and does not require any page reloading during use.

Pretty cool but not ideal !

Most of the time it returns an empty HTML file with some CSS and JavaScript links. It’s a trap :

  1. During initial render users have to wait longer (to load all resources including markup) which could be a huge pain on slow networks (up to 25 - 30s)
  2. Some crawlers would simply see all pages as empty

And when I say “empty” I mean that :

<div id="root"></div>

😎

Server side rendering

Unlike client side rendering (CSR) which uses the browser, SSR uses… the server. In other words the JavaScript is rendered with the server and then the response (with HTML markup) is sent to the browser.

Therefore you can leverage the benefits of the two approaches : speed/SEO and interactivity/ux.

A lot of frameworks such as Gatsby are using, amongst other things, this interesting mix.

So what is hydration/rehydration ?

Rehydration is pretty much the bridge between SSR and CSR. The idea is to achieve a fast First Contentful Paint with the server and then adding the remaining stuffs such as event listeners on client side.

In other words some parts of the code used to quickly generate the page is reused this time in the browser where there are some DOM APIs like window.

Source

Rehydration has a cost

Rehydration is not the ultimate technique. Depending on what you want to achieve you will have some trade-offs. The problem with rehydration is Time To Interactive.

Even if the page has a fast First Contentful Paint, the user cannot interact with it. It can be frustrating as sometimes the CSR part is quite slow.

For example, I don’t get why people are sometimes sharing codes or sheets as png/jpg images instead of something you can simply copy/paste to test/reuse. It’s kind of the same bad experience here (fortunately it’s transient). You can try to scroll down or click on something, it won’t work until the whole process is done.

Wrap up

Rehydration consists in 2 main parts : a pre-render with the server and a full render with the browser.

As this technique is not perfect at all there are some workarounds like the Two pass rendering or enhancements such as Progressive Rehydration but it might be more difficult to implement.