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

Real-time Updates with SignalR

Synchronize multiple client views in real-time using Hub-based communication.

In this lesson, you will learn how to synchronize state across multiple Blazor client views instantly using a SignalR Hub.

The Hub-Based Communication Model

Up until now, your Blazor components have been "islands"—they respond to user interaction locally. To make these components aware of each other in real-time, we introduce a SignalR Hub. Think of a Hub as a shared communication "switchboard" living on your server. When one client performs an action, it notifies the Hub, which then broadcasts that event to every other connected client simultaneously.

Implementing the Broadcast

To synchronize views, your Blazor component needs to act as both a sender and a listener. First, inject the HubConnection into your component. When a user changes the UI (for example, updating a shared dashboard value), the component sends that update to the Hub:

// Sending an update to the server
await hubConnection.SendAsync("UpdateDashboard", newData);

On the receiving end, you register a listener in the component’s lifecycle (usually in OnInitializedAsync) to react to these incoming broadcasts:

hubConnection.On<DashboardData>("ReceiveUpdate", (data) =>
{
    // Update local state and trigger a re-render
    this.sharedData = data;
    InvokeAsync(StateHasChanged);
});

Synchronizing Multiple Clients

The magic happens because the Hub maintains a persistent connection with every active browser session. When ReceiveUpdate triggers in your On handler, InvokeAsync(StateHasChanged) forces the Blazor RenderTree to update the DOM immediately. Because every client is running this same logic, they all update their local view the moment the Hub broadcasts the data. This creates the illusion of a single, shared application state even though each user is viewing the page independently.

By moving away from polling or manual refreshes and using this event-driven architecture, your Blazor components become synchronized puppets controlled by the central Hub.

Key Takeaway: SignalR enables real-time synchronization by transforming your components into event listeners that trigger automatic UI re-renders whenever the central Hub broadcasts a state change.