Hydration

In dioxus fullstack, the server renders the initial HTML for improved loading times. This initial version of the page is what most web crawlers and search engines see. After the initial HTML is rendered, the client makes the page interactive and takes over rendering in a process called hydration. Most of the time, you shouldn't need to think about hydration, but there are a few things you need to keep in mind to avoid hydration errors. To better understand hydration, let's walk through a simple example:

src/hydration.rs
fn Weather() -> Element {
    let mut weather = use_server_future(fetch_weather)?;

    rsx! {
        div {
            "{weather:?}"
        }
        button {
            onclick: move |_| weather.restart(),
            "Refetch"
        }
    }
}

Rendering the initial HTML

When the server receives a request to render the Weather component, it renders the page to HTML and serializes some additional data the client needs to hydrate the page. It will follow these steps to render our component:

  1. Run the component
  2. Wait until all server futures are resolved
  3. Serialize any non-deterministic data (like the weather future) for the client
  4. Render the HTML

Once the server finishes rendering, it will send this structure to the client as HTML:

Hydrating on the client

When the client receives the initial HTML, it hydrates the HTML by rerunning each component and linking each node that component renders to the node the server rendered. Rerunning each component lets the client re-construct some non-serializable state like event handlers and kick off any client side logic like use_effect and use_future.

It will follow these steps:

  1. Deserialize any non-deterministic data from the server (like the weather future)
  2. Run the component with the deserialized data. All server futures are immediately resolved with the deserialized data from the server.
  3. Hydrate the HTML sent from the server. This adds all event handlers and links the html nodes to the component so they can be moved or modified later

Hydration errors

For hydration to work, the component must render exactly the same thing on the client and the server. If it doesn't, you might see an error like this:

Uncaught TypeError: Cannot set properties of undefined (setting 'textContent')
at RawInterpreter.run (yourwasm-hash.js:1:12246)

Or this:

Error deserializing data:
Semantic(None, "invalid type: floating point `1.2`, expected integer")
This type was serialized on the server at src/main.rs:11:5 with the type name f64. The client failed to deserialize the type i32 at /path/to/server_future.rs

Non-deterministic data with server cached

You must put any non-deterministic data in use_server_future, use_server_cached or use_effect to avoid hydration errors. For example, if you need to render a random number on your page, you can use use_server_cached to cache the random number on the server and then use it on the client:

src/hydration.rs
// ❌ The random number will be different on the client and the server
let random: u8 = use_hook(|| rand::random());
// ✅ The same random number will be serialized on the server and deserialized on the client
let random: u8 = use_server_cached(|| rand::random());

Async loading with server futures

If you need render some data from a server future, you need to use use_server_future to serialize the data instead of waiting for the (non-deterministic) amount of time use_resource(...).suspend()? takes:

src/hydration.rs
// ❌ The server function result may be finished on the server, but pending on the client
let random: u8 = use_resource(|| random_server_function()).suspend()?().unwrap_or_default();
// ✅ Once the server function is resolved on the server, it will be sent to the client
let random: u8 = use_server_future(|| random_server_function())?()
    .unwrap()
    .unwrap_or_default();

Client only data with effects

If you need to grab some data that is only available on the client, make sure you get it inside of a use_effect hook which runs after the component has been hydrated:

src/hydration.rs
// ❌ Using a different value client side before hydration will cause hydration issues
// because the server rendered the html with another value
let mut storage = use_signal(|| {
    #[cfg(feature = "server")]
    return None;
    let window = web_sys::window().unwrap();
    let local_storage = window.local_storage().unwrap().unwrap();
    local_storage.set_item("count", "1").unwrap();
    local_storage.get_item("count").unwrap()
});
// ✅ Changing the value inside of an effect is fine because effects run after hydration
let mut storage = use_signal(|| None);
use_effect(move || {
    let window = web_sys::window().unwrap();
    let local_storage = window.local_storage().unwrap().unwrap();
    local_storage.set_item("count", "1").unwrap();
    storage.set(local_storage.get_item("count").unwrap());
});

Avoid side effects in server cached hooks

The dioxus fullstack specific hooks use_server_cached and use_server_future don't run the same on the server and the client. The server will always run the closure, but the client may not run the closure if the server serialized the result. Because of this, the code you run inside these hooks cannot have side effects. If it does, the side effects will not be serialized and it can cause a hydration mismatch error:

src/hydration.rs
// ❌ The state of the signal cannot be serialized on the server
let mut storage = use_signal(|| None);
use_server_future(move || async move {
    storage.set(Some(server_future().await));
})?;
// ✅ The value returned from use_server_future will be serialized on the server and hydrated on the client
let storage = use_server_future(|| async move { server_future().await })?;