›bobbyencoded_
/posts/newsletter/courses/about
/posts/newsletter/courses/about

The Decode

The week's AI & software news, decoded.

Subscribe →

// © 2026 BobbyEncoded Inc. — A Canadian corporation

← Back to Blog

Blazor Learning Path

Blazor Learning Path, Part 3: Advanced Blazor

November 2, 2026 · 15 min read

Blazor, C#, .NET, Razor, bUnit, Interview Prep, Performance

Part 1 covered the fundamentals and Part 2 covered real features. This part is the senior end: how render modes actually interact, why things run twice, how to keep a big UI fast, how to keep it safe, how to test it, and how to structure the solution. Everything targets .NET 10, and the code compiles (the bUnit tests at the end pass).

Render modes in depth

Part 1 listed the four modes. The rules about how they combine are what trip people up:

  • Render modes propagate down the tree. A component without its own @rendermode inherits its parent's. Put a mode on <Routes> in App.razor and the whole app is interactive; leave it off and each page or component chooses.
  • You can't switch to a different interactive mode inside an interactive component. A Server component can't contain a WebAssembly child. The Microsoft docs state this outright.
  • Parameters crossing from a static parent into an interactive child must be JSON-serializable. That means no RenderFragment or ChildContent: passing child content from a static parent to an interactive child fails at runtime. This is also why making MainLayout interactive in a per-page app doesn't work. The layout receives @Body as a render fragment.
  • RendererInfo tells you where you are: RendererInfo.Name is Static, Server or WebAssembly, and RendererInfo.IsInteractive says whether event handlers work yet. Use it to disable a button until the component is interactive.
<button @onclick="Save" disabled="@(!RendererInfo.IsInteractive)">Save</button>

Choosing a mode in practice:

If you need…Choose
SEO, content, simple forms, the fastest pagesStatic SSR, with interactivity only where needed
Internal tools, data that must stay on the server, quick start-upInteractive Server
Rich client-side behaviour, offline, lower server loadInteractive WebAssembly
Fast first visit and client-side laterInteractive Auto

For Auto and WebAssembly, remember that the component's code ships to the browser: anything in it, including connection strings or business rules you'd rather keep private, is visible. Server-only code belongs in the server project.

Prerendering, and the double call

Interactive components are prerendered by default: the server renders HTML first so the user sees content immediately, then the component starts again interactively. So OnInitializedAsync runs twice, which means two API calls and a flicker as the loading state reappears.

.NET 10 adds a declarative fix, the [PersistentState] attribute:

@page "/book-of-the-month"
@rendermode InteractiveAuto
@inject IBookService Books

@if (Pick is null)
{
    <p>Loading…</p>
}
else
{
    <h1>@Pick.Title</h1>
    <p>Rendering: @RendererInfo.Name</p>
}

@code {
    // Serialized into the prerendered HTML, restored when the component goes interactive,
    // so the API is called once instead of twice and the page doesn't flicker.
    [PersistentState]
    public Book? Pick { get; set; }

    protected override async Task OnInitializedAsync()
    {
        Pick ??= await Books.GetBookAsync(1);
    }
}

The property must be public. The value is serialized with System.Text.Json into the page. Two cautions from the docs: for WebAssembly and Auto, that data is visible in the browser, so never persist anything sensitive; and if the page is reached by enhanced (in-app) navigation, there's no prerender, so the restore only matters on full page loads. Before .NET 10, the same thing took the imperative PersistentComponentState API (RegisterOnPersisting plus TryTakeFromJson), which you'll still see in older code.

The other option is turning prerendering off for a component: @rendermode @(new InteractiveServerRenderMode(prerender: false)). You get one call, but the user sees nothing until the component is interactive.

Streaming rendering

For static SSR pages that wait on slow data, streaming rendering sends the page immediately with a placeholder, then streams the finished content over the same response:

@page "/stats"
@attribute [StreamRendering]

<h1>Club stats</h1>

@if (stats is null)
{
    <p>Crunching the numbers…</p>
}
else
{
    <p>@stats.BooksRead books read by @stats.Members members.</p>
}

@code {
    private Stats? stats;

    protected override async Task OnInitializedAsync()
    {
        await Task.Delay(1500); // a slow query
        stats = new Stats(BooksRead: 318, Members: 24);
    }

    private sealed record Stats(int BooksRead, int Members);
}

There's no SignalR, no WebAssembly, and no interactivity: just a faster-feeling page. It's often the right answer before making a page interactive just to show a spinner.

Performance

Blazor re-renders a component after its events, its parameter changes, and StateHasChanged calls. The tools, in the order I'd reach for them:

1. Don't render what isn't visible: Virtualize. For long lists, only the rows in view (plus a buffer) exist in the DOM:

<div style="height: 600px; overflow-y: auto">
    <Virtualize Items="Books" Context="book" ItemSize="48">
        <BookRow @key="book.Id" Book="book" />
    </Virtualize>
</div>

@code {
    // 20,000 books, but only the rows in view (plus a small buffer) exist in the DOM.
    [Parameter] public List<Book> Books { get; set; } = [];
}

When the data is too big to load at all, give it an ItemsProvider and fetch only the window being viewed:

<Virtualize ItemsProvider="LoadBooks" Context="book" ItemSize="48">
    <ItemContent><BookRow Book="book" /></ItemContent>
    <Placeholder><div class="row-skeleton">Loading…</div></Placeholder>
</Virtualize>

@code {
    [Parameter, EditorRequired] public Func<int, int, CancellationToken, Task<(IReadOnlyList<Book> Items, int Total)>> FetchPage { get; set; } = default!;

    // Asks the server only for the window the user is looking at.
    private async ValueTask<ItemsProviderResult<Book>> LoadBooks(ItemsProviderRequest request)
    {
        var (items, total) = await FetchPage(request.StartIndex, request.Count, request.CancellationToken);
        return new ItemsProviderResult<Book>(items, total);
    }
}

2. Skip renders that can't change anything: ShouldRender. By default, when a parent re-renders, children with parameters re-render too (Blazor can only skip them when every parameter is a known immutable primitive type). If your parameters are immutable records, you can be precise:

<div class="row">@Book.Title, @Book.Author (@Book.Year)</div>

@code {
    [Parameter, EditorRequired] public Book Book { get; set; } = default!;

    private Book? lastRendered;

    // Book is an immutable record, so "same reference" means "nothing changed".
    protected override bool ShouldRender()
    {
        if (ReferenceEquals(Book, lastRendered)) return false;
        lastRendered = Book;
        return true;
    }
}

ShouldRender isn't called for the first render, and it only works this simply because the data is immutable. With mutable objects you can't tell from the reference whether anything changed.

3. Keep identity stable: @key on list items (see Part 1), so reordering moves components instead of rebuilding them.

4. Watch the patterns that cause render storms: calling StateHasChanged in a loop, timers that re-render every few milliseconds, huge components that re-render everything for a one-field change (split them), and CascadingValues that change often (every consumer re-renders; mark values that never change with IsFixed="true").

On Interactive Server, also remember latency: every event is a network round trip. Debounce chatty inputs, and avoid @bind:event="oninput" on big forms over slow connections.

Security: MarkupString and XSS

Part 2 showed MarkupString for trusted HTML. When the HTML comes from users or from an external system you don't control, sanitize it first with an allow-list sanitizer such as HtmlSanitizer:

@using Ganss.Xss
@inject HtmlSanitizer Sanitizer

<article class="review">@((MarkupString)safeHtml)</article>

@code {
    // Written by a member in a rich-text box: untrusted.
    [Parameter, EditorRequired] public string ReviewHtml { get; set; } = "";

    private string safeHtml = "";

    // Strips <script>, event handlers like onerror=, javascript: URLs and anything not on the allow-list.
    protected override void OnParametersSet() => safeHtml = Sanitizer.Sanitize(ReviewHtml);
}

Registered as builder.Services.AddSingleton<HtmlSanitizer>();. Better still, ask whether you need HTML at all: if the source only uses line breaks or bold, render plain text and add the formatting in your own markup. Add a Content Security Policy as a second layer; Microsoft has a Blazor-specific CSP guide.

In the wild: a common case is an external API that returns text with HTML in it, a <br> here and a <b> there, and the quickest way to display it is a MarkupString cast. It works, and it quietly turns that API into a way to run script in your users' browsers if it's ever compromised or starts echoing user input. The standard is to treat any HTML you didn't write as untrusted: sanitize it, or convert the few tags you expect (split on <br> and render lines) and encode everything else.

Error boundaries

On Interactive Server, Microsoft's docs are blunt: Blazor treats most unhandled exceptions as fatal to the circuit. The user's session dies and they have to reload. Error boundaries contain the damage:

@page "/dashboard"
@rendermode InteractiveAuto

<h1>Dashboard</h1>

<ErrorBoundary @ref="chartBoundary">
    <ChildContent>
        <BooksPerYearChart Books="books" />
    </ChildContent>
    <ErrorContent Context="ex">
        <p class="error">The chart couldn't load. The rest of the page still works.</p>
        <button @onclick="() => chartBoundary?.Recover()">Try again</button>
    </ErrorContent>
</ErrorBoundary>

<ReadingListBadge />

@code {
    private ErrorBoundary? chartBoundary;
    private readonly List<Book> books = [new(1, "Dune", "Frank Herbert", 1965)];
}
  • Scope them narrowly, around widgets that can fail independently. A boundary in the layout shows its error UI on every page until it's recovered.
  • Recover() resets the boundary and re-renders its content. Call it from an event (like the button) or OnParametersSet, never from rendering logic, or a component that throws every time loops forever.
  • Boundaries are for the unexpected. Expected failures (a 404 from your API, a validation error) should still be handled with try/catch and a proper UI state.

Testing with bUnit

bUnit renders components in memory, without a browser, so component tests run as fast as unit tests. Recent versions (v2) use BunitContext and Render<T>:

using Bunit;

public class ReadingGoalTests : BunitContext
{
    [Fact]
    public void Finishing_a_book_updates_the_progress()
    {
        var cut = Render<ReadingGoal>(); // cut = component under test

        cut.Find("button").Click();

        cut.Find("p").MarkupMatches("<p>1 of 12 read (8%)</p>");
    }

    [Fact]
    public void Favourite_button_raises_the_callback_with_the_title()
    {
        string? favourited = null;

        var cut = Render<BookCard>(ps => ps
            .Add(p => p.Title, "Dune")
            .Add(p => p.OnFavourite, (string title) => favourited = title));

        cut.Find("button").Click();

        Assert.Equal("Dune", favourited);
    }
}

Running them against the components from Part 1:

Passed!  - Failed:     0, Passed:     3, Skipped:     0, Total:     3, Duration: 284 ms - BookClub.Tests.dll (net10.0)

(Three because the xUnit template ships with an empty sample test.) Register fakes for injected services with Services.AddSingleton<IBookService>(fake), and use bUnit's JS interop emulation (JSInterop.SetupModule(...)) for components that call JavaScript. Keep logic out of components where you can, like the chart's grouping in Part 2, and it's testable with no bUnit at all.

Solution structure

The Blazor Web App template gives you two projects when you choose WebAssembly or Auto interactivity:

  • App (server): hosting, API endpoints, server-only components and services, and anything that touches the database or secrets.
  • App.Client: components that may run in the browser, plus the services they need.

Most real apps add a shared contracts project, or keep contracts in the client project, with the request and response types both sides agree on. Naming them as commands (change something) and queries (read something) keeps intent obvious:

// Shared by the server (handlers) and the client (typed API calls).
// One file per message keeps them easy to find; they're grouped here for the post.
public sealed record GetUpcomingMeetingsQuery(int ClubId, int Take = 5);

public sealed record MeetingSummary(Guid Id, DateOnly Date, string BookTitle, int Rsvps);

public sealed record ScheduleMeetingCommand(int ClubId, DateOnly Date, int BookId);

public sealed record ScheduleMeetingResult(Guid MeetingId);

And a typed client that speaks in those terms:

public sealed class MeetingsClient(HttpClient http)
{
    public async Task<IReadOnlyList<MeetingSummary>> GetUpcomingAsync(GetUpcomingMeetingsQuery query, CancellationToken ct = default) =>
        await http.GetFromJsonAsync<List<MeetingSummary>>(
            $"api/clubs/{query.ClubId}/meetings?take={query.Take}", ct) ?? [];

    public async Task<ScheduleMeetingResult> ScheduleAsync(ScheduleMeetingCommand command, CancellationToken ct = default)
    {
        var response = await http.PostAsJsonAsync($"api/clubs/{command.ClubId}/meetings", command, ct);
        response.EnsureSuccessStatusCode();
        return (await response.Content.ReadFromJsonAsync<ScheduleMeetingResult>(ct))!;
    }
}

The server handles each message in an endpoint (or a handler behind a mediator library, if the team uses one). Microsoft's eShop reference app is the best place to see these pieces at scale. Two more conventions worth adopting: one serializer (System.Text.Json) on both sides of every boundary, because two serializers with different defaults disagree about casing and dates in ways that only show up at runtime; and feature folders (everything for meetings together) over technical folders (all DTOs together).

In the wild: for work that takes minutes (a report, an import, a call to a slow external service), a common UI pattern is to start the job, then poll a status endpoint every few seconds. It's simple and works through any proxy, and it's a fine default. The alternative is push: the server notifies the browser when the job finishes, via SignalR (which Interactive Server already uses under the hood). Push is more responsive and saves the empty polls, but it adds connection management and scale-out concerns. If you poll, back off (2s, 4s, 8s…) and cap the total wait, so a stuck job doesn't mean a browser polling forever.

Big file uploads: straight to Blob storage

Blazor's InputFile can stream a file to your server, but for large files the better design is to keep the bytes away from your server entirely. The server hands out a short-lived, write-only URL for one blob (a SAS, the valet key pattern from my cloud structure patterns post), and the browser uploads directly:

// Server: issue a ticket
app.MapGet("/api/uploads/cover", (string fileName, BlobContainerClient covers) =>
{
    var blobName = $"{Guid.NewGuid():N}{Path.GetExtension(fileName)}"; // never trust the client's name
    var blob = covers.GetBlobClient(blobName);

    // Create + Write on this one blob only, valid for 10 minutes.
    // GenerateSasUri needs a shared-key credential; with managed identity, use a user delegation key.
    var sas = blob.GenerateSasUri(
        BlobSasPermissions.Create | BlobSasPermissions.Write,
        DateTimeOffset.UtcNow.AddMinutes(10));

    return Results.Ok(new { UploadUrl = sas, BlobName = blobName });
}).RequireAuthorization();
@* Client: upload with the ticket *@
@inject HttpClient Http

<InputFile OnChange="UploadAsync" accept="image/*" />
<p>@status</p>

@code {
    private const long MaxBytes = 50 * 1024 * 1024; // 50 MB
    private string status = "";

    private async Task UploadAsync(InputFileChangeEventArgs e)
    {
        var file = e.File;

        // 1. Ask our API for a short-lived, write-only URL for one blob (the valet key).
        var ticket = await Http.GetFromJsonAsync<UploadTicket>(
            $"api/uploads/cover?fileName={Uri.EscapeDataString(file.Name)}");

        // 2. Send the bytes straight to Blob Storage. Our server never sees them.
        await using var stream = file.OpenReadStream(MaxBytes);
        using var content = new StreamContent(stream);
        content.Headers.ContentType = new(file.ContentType);
        content.Headers.Add("x-ms-blob-type", "BlockBlob");

        using var direct = new HttpClient(); // no base address: the SAS URL is absolute
        var response = await direct.PutAsync(ticket!.UploadUrl, content);

        status = response.IsSuccessStatusCode ? "Uploaded." : $"Upload failed: {(int)response.StatusCode}";
    }

    private sealed record UploadTicket(Uri UploadUrl, string BlobName);
}

Things that make this production-ready: CORS on the storage account for your site's origin; a size cap (OpenReadStream throws past MaxBytes, which defaults to only 500 KB if you don't pass one); a confirmation call afterwards so your API records the blob and can validate it (type, size, malware scan) before it's used; and a lifecycle rule to clean up blobs that were uploaded but never confirmed. This runs in the browser, so it belongs in a WebAssembly or Auto component; on Interactive Server the file would stream through the circuit, which is exactly what we're avoiding.

Check yourself: questions and answers

1. Can a WebAssembly component contain an Interactive Server child?

No. Render modes propagate down, and you can't switch to a different interactive mode inside an interactive component. Mixing modes happens at the boundary between static and interactive parts of the page.

2. Why can't a static parent pass ChildContent to an interactive child?

Parameters crossing into an interactive component must be serialized, and a RenderFragment is a delegate, which can't be. Restructure so the interactive component owns that markup.

3. How do you avoid the double data load caused by prerendering?

Persist the prerendered state, with [PersistentState] on a public property in .NET 10 (or PersistentComponentState in earlier versions), or disable prerendering for that component.

4. What is streaming rendering?

For static SSR, the server sends the page with placeholder content immediately and streams the updated markup when async work finishes, in the same response. It gives fast perceived load without making the page interactive.

5. How do you render a list of 50,000 items?

Virtualize, ideally with an ItemsProvider that fetches only the visible window, plus @key on rows and lightweight row components.

6. When would you override ShouldRender?

When a component re-renders often because its parent does, but its output depends on data you can cheaply compare, such as immutable records compared by reference. It isn't called on the first render.

7. What happens to an unhandled exception on Interactive Server?

It's treated as fatal to the circuit; the user must reload. Error boundaries contain failures to part of the UI, and expected errors should be handled with try/catch.

8. How do you safely render HTML from an external source?

Don't cast it straight to MarkupString. Sanitize it with an allow-list sanitizer, or avoid HTML by rendering text and adding formatting yourself, and add a Content Security Policy as defence in depth.

9. How do you unit test a Blazor component?

bUnit renders it in memory: render, find elements, trigger events, assert on markup, with fake services registered in the test context and JS interop emulated.

10. How would you handle multi-gigabyte uploads?

Have the server issue a short-lived, write-only SAS URL for one blob and upload directly from the browser to storage, then confirm the upload with the API. The server never handles the bytes.

Go deeper

  • Cloud Structure and Migration Patterns: the valet key pattern behind direct uploads
  • Command, Chain of Responsibility, Mediator and Template Method: the patterns behind commands, queries and mediators
  • Testing in .NET
  • React Learning Path, Part 3: Server Components and concurrent rendering, React's answers to the same problems

Next: Blazor vs React, the same ideas in two stacks.

Further reading

  • Microsoft Learn, Render modes and Prerendering
  • Microsoft Learn, Prerendered state persistence
  • Microsoft Learn, Rendering, Rendering performance and Virtualization
  • Microsoft Learn, Handle errors
  • Microsoft Learn, Content Security Policy for Blazor
  • Microsoft Learn, Test Razor components and bUnit
  • Microsoft Learn, File uploads and Create a service SAS with .NET
  • Microsoft Learn, Blazor SignalR guidance
  • Microsoft, eShop reference application and Blazor samples
  • HtmlSanitizer
← Previous

More Code, Not More Software

Next →

Cloud Structure and Migration Patterns and the GoF Patterns Inside Them

Thoughts on this?

Tell me on X: @bobbyencoded · Share this post on X

Want more like this? Subscribe to The Decode, a weekly email on the AI and developer news worth your time.