Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 41 ยท Hosting Models and Deployment

Prerendering and Streaming Rendering in Blazor

Understand why interactive Blazor components run twice, how to avoid duplicate data loads and flicker with persisted state, and when streaming rendering shows content sooner.

When a browser asks for an interactive Blazor page, the server does not wait to boot a circuit or download WebAssembly before answering. It prerenders: it runs your component on the server once, produces plain HTML and sends it immediately, so users see content fast and search engines can read it. Only afterwards does the interactive runtime start and take over the page. This is great for perceived speed and SEO, and it has consequences that surprise many developers: your lifecycle methods can run twice.

This lesson explains the two-phase life of a component, shows how to avoid loading the same data twice, and introduces streaming rendering for slow data. The component snippets are real and read-only; the runnable parts are stand-ins in C# that make the lifecycle visible.

Two phases

sequenceDiagram
    participant B as Browser
    participant S as Server
    B->>S: GET /products
    S->>S: Phase 1: prerender (OnInitializedAsync runs)
    S-->>B: HTML (visible immediately)
    B->>S: Open circuit (or download WebAssembly)
    S->>S: Phase 2: interactive render (OnInitializedAsync runs AGAIN)
    S-->>B: Diff: page becomes interactive

The same component is created twice: once for the HTML, once for the live version.

Consequences of this model:

  • OnInitialized and OnInitializedAsync run in both phases (a new component instance each time).
  • Anything you load in phase 1 is lost when phase 2 begins, unless you hand it over.
  • Event handlers, JavaScript interop and anything needing a browser do not work during prerendering, because there is no browser yet. IJSRuntime calls throw in OnInitialized; do them in OnAfterRenderAsync, which only runs in the interactive phase.

The flicker problem

Imagine a page that loads products in OnInitializedAsync. Phase 1 loads them and renders a full list. Phase 2 creates a new component, whose products field is empty again, so it renders "Loading..." until the second load finishes, then the list reappears. The user sees content, then a blink back to a spinner, then content. It also means two database queries per visit.

You can reproduce it without Blazor: the two phases are just two component instances.

C# Stand-in: a component initialized twice

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Two queries, and a visible "Loading..." in the middle. Blazor's answer is to persist the prerendered state and restore it.

Persisting state across the two phases

Blazor serializes chosen values into the HTML of phase 1 and hands them back to phase 2. In modern Blazor you mark a property with [PersistentState]:

RAZOR
@page "/products"
@inject IProductService Products

@if (items is null)
{
    <p>Loading...</p>
}
else
{
    <ul>@foreach (var p in items) { <li>@p.Name</li> }</ul>
}

@code {
    [PersistentState]
    public List<Product>? items { get; set; }

    protected override async Task OnInitializedAsync()
    {
        items ??= await Products.GetAllAsync();   // only loads if nothing was restored
    }
}

On phase 2, items is already filled from the serialized page data, so ??= skips the second query and nothing flickers. Older projects use the PersistentComponentState service with RegisterOnPersisting and TryTakeFromJson to do the same by hand. Persisted data is embedded in the HTML sent to the user, so never persist secrets, and keep it small.

This stand-in models the handover with a simple store:

C# Stand-in: persisting state between phases

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

One query, no flicker. That is the whole purpose of persisted state.

Turning prerendering off

Sometimes prerendering is the wrong choice: a component that is useless without the browser (a canvas editor), or whose first render depends on JavaScript. You can disable it for a component or an app:

RAZOR
@rendermode @(new InteractiveServerRenderMode(prerender: false))

Without prerendering you lose the instant HTML and the SEO benefit, but you also avoid the double initialization. Use it deliberately, not by default. In WebAssembly-only projects there is no prerendering unless you add a server host for it.

Streaming rendering

Prerendering still waits for OnInitializedAsync to finish before sending the HTML. If one query takes three seconds, the whole page waits. Streaming rendering (for static SSR components) sends the page quickly with the parts that are ready, then streams the rest into place when the slow work completes, without a full reload.

RAZOR
@page "/reports"
@attribute [StreamRendering]
@inject IReportService Reports

<h1>Reports</h1>   @* arrives immediately *@

@if (rows is null)
{
    <p>Loading report...</p>   @* sent first *@
}
else
{
    <ReportTable Rows="rows" />   @* streamed in later *@
}

@code {
    private Report[]? rows;

    protected override async Task OnInitializedAsync()
    {
        rows = await Reports.BuildAsync();   // slow
    }
}

The "Loading report..." HTML arrives right away and the browser replaces it with the table when the server finishes. No WebSocket and no WebAssembly are required, so you keep static SSR's low cost and still avoid a blank wait. This model shows the timing difference:

C# Stand-in: time to first content, buffered vs streamed

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Both finish at the same moment; streaming just lets the user see the heading and a placeholder 300 ms sooner. For interactive modes the equivalent idea is to show placeholders in your own component while data loads.

Practical rules

  • Write OnInitializedAsync so it can run twice safely: no one-time side effects such as sending an email or incrementing a counter.
  • Put browser-only work in OnAfterRenderAsync(bool firstRender).
  • Persist expensive data you load during prerendering, and keep the payload small and non-secret.
  • Use streaming rendering for slow queries on mostly static pages.
  • Disable prerendering only when a component truly cannot render without the browser.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why can OnInitializedAsync run twice for an interactive component?

    Prerendering creates a component for the HTML; the interactive phase creates a new instance.
  2. 2. What does [PersistentState] help with?

    The value is serialized into the page and restored, avoiding duplicate loads and flicker.
  3. 3. Where should JavaScript interop run to be safe during prerendering?

    OnAfterRender runs only once the component is interactive and a browser exists.
  4. 4. What does streaming rendering improve?

    The page appears immediately with placeholders, then slow sections are streamed into place.

Summary

  • Interactive components are prerendered to HTML, then re-created interactively, so initialization can run twice.
  • Persist prerendered data ([PersistentState]) to avoid duplicate queries and flicker; never persist secrets.
  • Do browser-only work in OnAfterRenderAsync.
  • Prerendering can be disabled per component when it does more harm than good.
  • Streaming rendering shows fast content first and streams slow content in, without a live connection.

Next: Publishing and Deploying Blazor Apps