Skip to main content

React Hydration

React hydration is the process by which React attaches event handlers to existing html. It occurs when you prerender React using either Server Side Rendering (SSR) or Static Site Generation (SSG). React requires that that prerendered html and and the React tree that is rendered during hydration match exactly. If they don't, you'll get React hydration errors.

Let's look at the sequence of events for a Causal hook used on an SSG page:

  1. The page is statically generated. During the generation phase any Causal hook comes back as undefined (because during SSG hooks don't get network responses)
  2. You view the page.
    • During the first render, the hook comes back as undefined. This matches the SSG render
    • Once the network request returns a second render is triggered filling in the data
  3. You refresh the page.
    • During the first render the data is immediately available (because it was cached). If the hook returned this data immediately, it would cause a React hydration error because it would not match the SSG render. So, by default, the hook returns undefined and then triggers an immediate follow on update.

If you are not using SSG, this behavior is slightly suboptimal. You can change it so that cached reads are returned immediately by setting the defaultPageType in CausalOption using initCausal

  initCausal({defaultPageType: "CSR"})

This behavior can also be changed on a page (or even component) basis using OptionContext

    <OptionContext.Provider value={{ defaultPageType: "SSG" }}>
{children}
</OptionContext.Provider>

Here are some additional articles on React hydration: