Articles in this section
Category / Section

How to Use Stream Rendering While Prerendering in Blazor WebApp?

4 mins read

Overview

With .NET 8, stream rendering enables Blazor Web Apps to send parts of a page to the browser as they become available during prerendering, improving perceived performance, especially for components like the Syncfusion Blazor DataGrid that rely on long-running asynchronous operations (e.g., API calls).

This article shows how to use stream rendering with the Syncfusion Blazor DataGrid to enhance the user experience by reducing initial load delays.

Why Use Stream Rendering?

Traditionally, during prerendering Blazor Server waits for all asynchronous tasks to complete before sending the rendered page to the client. This can cause noticeable delays if components like the DataGrid depend on slow API responses.

With stream rendering, the page is rendered and sent to the client immediately with placeholder content. Once async operations complete, updated content is streamed and patched into the DOM without a full reload.

Prerequisites:

  • .NET 8 SDK
  • Blazor Web App with prerendering enabled

How to Enable Stream Rendering in Syncfusion Blazor DataGrid?

The following DataGrid.razor component demonstrates how to implement stream rendering to progressively load content while fetching data asynchronously for the SfGrid. To ensure a smooth transition from prerendered to interactive mode and prevent UI flickering, the component also uses persistent prerendered state with the PersistentComponentState service.

DataGrid.razor:

@page "/"
@using StreamRendering.Models
@using StreamRendering.Services
//Injects a service to fetch order data
@inject OrderService OrderService
@implements IDisposable
//Used here to prevent flickering during the transition from prerendered to interactive mode.
@inject PersistentComponentState ApplicationState
//Enables stream rendering for this component
@attribute [StreamRendering]

//Displays a loading message while the data is being fetched asynchronously during prerendering.
//Hidden once the data is available.
<div style="@((Orders == null) ? "" : "display: none;")">
    <p><em>Loading data...</em></p>
</div>
//Renders the Syncfusion Blazor DataGrid once the data is loaded.
//Uses conditional styling to hide the grid until data is ready.
<SfGrid DataSource="@Orders" style="@((Orders == null) ? "display: none;" : "")">
    <GridColumns>
        <GridColumn Field=@nameof(Order.OrderID) HeaderText="Order ID" TextAlign="TextAlign.Right" Width="120"></GridColumn>
        <GridColumn Field=@nameof(Order.CustomerID) HeaderText="Customer ID" Width="150"></GridColumn>
        <GridColumn Field=@nameof(Order.OrderDate) HeaderText="Order Date" Format="d" Type="ColumnType.Date" TextAlign="TextAlign.Right" Width="130"></GridColumn>
        <GridColumn Field=@nameof(Order.Freight) Format="C2" TextAlign="TextAlign.Right" Width="120"></GridColumn>
        <GridColumn Field=@nameof(Order.ShipCountry) HeaderText="Ship Country" Width="150"></GridColumn>
    </GridColumns>
</SfGrid>

@code {
    private List<Order> Orders { get; set; }
    
    private PersistingComponentStateSubscription persistingSubscription;

    //The `OnInitializedAsync` method fetches data from an injected service.
    //This simulates a real-world scenario where data is loaded from an external API.
    protected override async Task OnInitializedAsync()
    {
        var statedLoaded = ApplicationState.TryTakeFromJson<List<Order>>(nameof(Orders), out var restored);
        Orders = statedLoaded && restored != null ? restored : await OrderService.GetOrdersAsync();
        persistingSubscription = ApplicationState.RegisterOnPersisting(PersistData);
    }
    private Task PersistData()
    {
        ApplicationState.PersistAsJson(nameof(Orders), Orders);
        return Task.CompletedTask;
    }
    void IDisposable.Dispose() => persistingSubscription.Dispose();
} 

OrderService.cs:

using System.Net.Http;
using System.Net.Http.Json;
using System.Threading.Tasks;
using System.Collections.Generic;
using StreamRendering.Models;
namespace StreamRendering.Services
{   
   public class OrderService
   {
       private readonly HttpClient _httpClient;

       public OrderService(HttpClient httpClient)
       {
           _httpClient = httpClient;
       }

       public async Task<List<Order>> GetOrdersAsync()
       {
           return await _httpClient.GetFromJsonAsync<List<Order>>("https://blazor.syncfusion.com/services/production/api/Orders/");
       }
   }
} 

Key Benefits:

  • Faster perceived load time: Users see the page structure immediately.
  • Improved user experience: Asynchronous operations during prerendering no longer block the entire page from rendering.

Resources:

Conclusion:

We hope this article helped you learn how to use stream rendering during prerendering in Blazor Web Apps with Syncfusion components for faster load times.

You can refer to our Blazor General feature tour page to learn about its other groundbreaking features. You can also explore our Documentation to understand how to present and manipulate data. For current customers, our Blazor components are available on the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to evaluate our Blazor components.

If you have any questions or require clarifications, please let us know in the comments below. You can also contact us through our support forums,Direct-Trac or feedback portal, or the feedback portal. We are always happy to assist you!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please  to leave a comment
Access denied
Access denied