Course contentsShow
← C#
Lesson 1344 of 1,90812. Modern Frontend with Razor and BlazorFree lesson

State Recovery in Blazor Server

Handle connection disruptions in Blazor Server by restoring transient state.

Mastering State Recovery in Blazor Server

In this lesson, you will learn how to maintain user progress during transient connection interruptions in Blazor Server applications.

The Problem: Volatile Memory

In Blazor Server, the UI state lives in the server's memory, associated with a specific SignalR connection. If a user’s internet flickers or they refresh the browser, that connection is dropped, and the server-side circuit is often disposed of. When the user reconnects, they are essentially starting a fresh session, and all their unsaved, transient data—like form entries or current page filters—is wiped out.

The Solution: Protecting Your State

To recover from this, you must offload transient state to a persistent store that survives circuit reconnection. Since we have already covered Managing Browser Storage (Lesson 23), we can use the localStorage or sessionStorage via JavaScript Interop to "checkpoint" your component’s data.

When a user modifies a state, you serialize the data to a storage provider. Upon initialization of your component, you check that storage for any existing data before starting fresh.

protected override async Task OnInitializedAsync()
{
    // Try to recover state from storage
    var savedState = await LocalStorage.GetItemAsync<MyViewModel>("user-form-data");
    
    if (savedState != null)
    {
        CurrentData = savedState;
    }
}

private async Task HandleInput()
{
    // Persist every time state changes
    await LocalStorage.SetItemAsync("user-form-data", CurrentData);
}

Bridging the Gap

When the connection is re-established, Blazor Server automatically attempts to restore the UI. By hooking into the component lifecycle—specifically OnInitialized—and checking your persistent storage, you ensure that the component re-renders with the exact data the user had before the disruption. This provides a "SPA-like" experience where the user feels as though the connection drop never occurred, as the state is pulled back into the application immediately upon reconnection.

Key Takeaway: By combining browser-side storage with component lifecycle hooks, you can reliably bridge the gap between volatile server circuits and persistent user experience.