Search code examples
data-bindingblazorblazor-server-side

How to reduce the amount of data transferred with Blazor server


I have a blazor component that fetch data from a service and then render data into a table.

This is my scenario:

  • The service returns a list of objects, each object contains a large set of properties and an object hierarchy
  • The user interface must only display a small amount of this data, therefore only some @myObject.MyProperty properties are displayed
@page "/fetchdata"
@inject WeatherForecastService ForecastService

@if (forecasts == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <table class="table">
        <thead>
            <tr>
                <th>Date</th>
                <th>Temp. (C)</th>
                <th>Temp. (F)</th>
                <th>Summary</th>
            </tr>
        </thead>
        <tbody>
            @foreach (var forecast in forecasts)
            {
                <tr>
                    <td>@forecast.Date.ToShortDateString()</td>
                    <td>@forecast.TemperatureC</td>
                    <td>@forecast.TemperatureF</td>
                    <td>@forecast.Summary</td>
                </tr>
            }
        </tbody>
    </table>
}

@code {
    private List<WeatherForecast> forecasts;

    protected override async Task OnInitializedAsync()
    {
        forecasts = ForecastService.List;
        ForecastService.MyEvent += _Event;
    }

    private void _Event(object sender, EventArgs e)
    {
        InvokeAsync(StateHasChanged);
    }
}

So in this case WeatherForecast is a large object, but only a small set of its properties are displayed. Is this scenario already optimized by the Blazor or does the server always "serve" the entire object to the client?


Solution

  • It is effectively 'optimized' to send only the changes.

    https://learn.microsoft.com/en-us/aspnet/core/blazor/hosting-models?view=aspnetcore-3.1#comparison-to-server-rendered-ui

    From the Blazor docs (from Blazor Server section):

    A UI update in Blazor is triggered by:

    User interaction, such as selecting a button. App triggers, such as a timer. The graph is rerendered, and a UI diff (difference) is calculated. This diff is the smallest set of DOM edits required to update the UI on the client. The diff is sent to the client in a binary format and applied by the browser.