Learn Blazor Β· 12/15

Advanced Component Architecture

8 min read

Course: Blazor
Difficulty: Advanced 🧠
Time to Read: 15 Minutes


πŸ‘‹ Welcome Back, Camper!

So, you've mastered the basics. You can bind data, handle clicks, and maybe even inject a service or two. But let's be honest: your current codebase might look a bit like a plate of spaghetti dropped on a tiled floorβ€”functional, but messy.

Today, we are graduating from "making it work" to "making it scalable." We are talking about Architecture.

In this module, we are going to look at how to build components that are reusable, generic, and performant. If you've ever found yourself copy-pasting an entire table component just to change Customer to Product, this guide is your salvation.

Let's dive in. πŸš€


1. RenderFragments: Building Reusable Templated Components

πŸ›‘ The Problem

Imagine you are building a UI library for your company. You need a Card component.
At first, you hardcode it:

html
<div class="card">
    <h3>User Profile</h3>
    <p>Name: John Doe</p>
</div>

But then your boss walks in: "Hey, can we use that card for the Weather Widget? And the Stock Ticker? And a picture of my cat?"

If you stick to basic properties, you'll end up with a mess of if/else statements inside your Card component trying to figure out what to display.

βœ… The Solution: RenderFragment

Definition: A RenderFragment is a delegate that represents a segment of UI content. It allows you to pass Razor syntax (HTML and components) into another component as a parameter.

In simple terms, instead of passing just a string (like Title="Hello"), you pass a chunk of HTML to be rendered inside the component.

πŸ’» How to Implement

The "ChildContent" Convention

By default, if you define a property named ChildContent of type RenderFragment, Blazor automatically captures whatever is inside the opening and closing tags of your component.

1. The Reusable Component (FancyCard.razor)

csharp
<div class="fancy-card-border">
    <!-- We decide WHERE the content goes, you decide WHAT the content is -->
    @ChildContent
</div>

@code {
    [Parameter]
    public RenderFragment? ChildContent { get; set; }
}

2. Consuming it (Home.razor)

html
<FancyCard>
    <!-- This HTML is passed as the ChildContent -->
    <h3>Cat Photo 🐱</h3>
    <img src="cat.jpg" />
</FancyCard>

<FancyCard>
    <!-- This HTML is re-using the same wrapper! -->
    <h3>Stock Price πŸ“‰</h3>
    <p>Stonks only go down.</p>
</FancyCard>

Named RenderFragments (Multiple Slots)

What if you need a specific Header, Body, and Footer? One ChildContent isn't enough.

1. The Component (LayoutCard.razor)

html
<div class="card">
    <div class="card-header">
        @Header <!-- Inject Header here -->
    </div>
    <div class="card-body">
        @BodyContent <!-- Inject Body here -->
    </div>
</div>

@code {
    [Parameter] public RenderFragment? Header { get; set; }
    [Parameter] public RenderFragment? BodyContent { get; set; }
}

2. Consuming it

html
<LayoutCard>
    <Header>
        <strong>Warning!</strong>
    </Header>
    <BodyContent>
        <p>You are about to delete the production database. Good luck.</p>
    </BodyContent>
</LayoutCard>

Industry Tip: You will see this pattern everywhere in libraries like MudBlazor or Radzen. It is the gold standard for layout components.


2. Generic Typed Components (@typeparam)

πŸ›‘ The Problem

You have a list of Users and you built a beautiful Table component to display them.
Now you have a list of Products.
You copy-paste UserTable.razor, rename it ProductTable.razor, and change the List<User> property to List<Product>.

Then you do it again for Orders.
Then again for AuditLogs.

You are violating the DRY principle (Don't Repeat Yourself). The logic for the table (pagination, sorting, CSS) is the same; only the Data Type changes.

βœ… The Solution: Generics

Definition: Generic components allow you to define a component that can accept different data types, specified at the time of use via the @typeparam directive.

πŸ’» How to Implement

1. The Generic Component (GenericList.razor)
We use @typeparam TItem to tell Blazor: "I don't know what this type is yet, let's call it TItem."

csharp
@typeparam TItem

<div class="list-container">
    @foreach (var item in Items)
    {
        <!-- We use a RenderFragment that accepts TItem as a parameter -->
        <div class="list-item">
            @ItemTemplate(item)
        </div>
    }
</div>

@code {
    // The list of data (could be Users, Products, etc.)
    [Parameter] public List<TItem> Items { get; set; } = new();

    // The template that defines how to draw ONE row
    [Parameter] public RenderFragment<TItem> ItemTemplate { get; set; } = default!;
}

2. Consuming it (Home.razor)
Blazor is usually smart enough to infer the type based on the Items you pass it!

html
<h3>User List</h3>
<GenericList Items="myUsers">
    <ItemTemplate Context="user">
        <!-- 'user' here is strongly typed as a User object! -->
        <strong>@user.Name</strong> - @user.Email
    </ItemTemplate>
</GenericList>

<h3>Product List</h3>
<GenericList Items="myProducts">
    <ItemTemplate Context="product">
        <!-- 'product' here is strongly typed as a Product object! -->
        <span>SKU: @product.Sku (@product.Price)</span>
    </ItemTemplate>
</GenericList>

@code {
    List<User> myUsers = ...;
    List<Product> myProducts = ...;
}

Fun Fact: The Context attribute defaults to the name context if you don't specify it. But renaming it to user or product makes your code much more readable. Otherwise, you end up with nested loops of context.Name inside context.Id, which is a debugging nightmare. 😡


3. DynamicComponent: Rendering UI Elements at Runtime

πŸ›‘ The Problem

You are building a dashboard. The user selects an option from a dropdown: "Show Chart", "Show Grid", or "Show Map".

The novice approach looks like the "Switch Statement of Doom":

csharp
@if (selectedType == "Chart") { <ChartComponent /> }
else if (selectedType == "Grid") { <GridComponent /> }
else if (selectedType == "Map") { <MapComponent /> }
// ... 20 more else ifs later ...

This is hard to maintain. If you add a new widget, you have to modify the UI code.

βœ… The Solution: <DynamicComponent>

Definition: DynamicComponent is a built-in Blazor component that renders a component instance based on a Type value passed to it at runtime.

πŸ’» How to Implement

You pass it a Type (the class name of the component) and a Dictionary of Parameters.

1. The Setup

csharp
@page "/dynamic-dashboard"

<select @bind="selectedComponentType">
    <option value="@typeof(WeatherWidget)">Weather</option>
    <option value="@typeof(StockWidget)">Stocks</option>
</select>

<hr />

<div class="widget-container">
    <!-- MAGIC HAPPENS HERE -->
    <DynamicComponent Type="selectedComponentType" Parameters="componentParams" />
</div>

@code {
    // Default to WeatherWidget
    Type selectedComponentType = typeof(WeatherWidget);

    // If your components need parameters, pass them here
    Dictionary<string, object> componentParams = new()
    {
        { "Theme", "Dark" },
        { "RefreshRate", 5000 }
    };
}

2. The Widgets (for context)

  • WeatherWidget.razor: Accepts Theme.
  • StockWidget.razor: Accepts RefreshRate.

When the user changes the dropdown, Blazor swaps the component instantly. No if/else required.

Industry Scenario: This is exactly how CMS (Content Management Systems) in Blazor work. The database says "Render a HeroBanner here," and DynamicComponent does the job without the page knowing what a "HeroBanner" is ahead of time.


4. Optimizing Renders with the ShouldRender Method

πŸ›‘ The Problem

Blazor is fast, utilizing a virtual DOM (render tree) to calculate differences. However, "calculating differences" takes CPU time.

Imagine a page with a High-Speed Stock Ticker updating every 100ms and a giant Data Grid with 5,000 rows below it.

Every time the stock ticker updates, Blazor might try to check if the Data Grid needs updating too. If the Grid re-renders (re-diffs) 10 times a second, your browser will freeze, and your users will cry.

βœ… The Solution: ShouldRender()

Definition: ShouldRender is a lifecycle method you can override. It returns a boolean.

  • true: "Go ahead, check my DOM for changes." (Default)
  • false: "I am fine. Don't look at me. Save your CPU cycles."

πŸ’» How to Implement

The Heavy Component (HeavyGrid.razor)

csharp
<h3>Massive Grid</h3>
<!-- Imagine 5000 rows here -->

@code {
    [Parameter] public List<string> Data { get; set; }

    // Optimization Logic
    protected override bool ShouldRender()
    {
        // Only render if the specific condition is met
        // For example: preventing render if the incoming data is exactly the same reference
        // OR simply creating a "Freeze" toggle.
        return !IsFrozen;
    }

    private bool IsFrozen = false;
}

Practical Usage Pattern:
Usually, Blazor is smart. But if you have a component that receives a parameter that changes frequently (like a timer tick) but the visual output shouldn't change, you force ShouldRender to return false.

csharp
@code {
    private int _lastHash;

    protected override bool ShouldRender()
    {
        // 1. Calculate a hash of the data
        var currentHash = MyComplexData.GetHashCode();
        
        // 2. If data hasn't changed, strictly tell Blazor to STOP.
        if (currentHash == _lastHash)
        {
             return false; 
        }

        _lastHash = currentHash;
        return true;
    }
}

Warning: Don't overuse this. Premature optimization is the root of all evil. Only reach for ShouldRender when you actually notice a lag in the UI or look at the profiler and see excessive rendering events.


πŸ“ Summary Checklist

  1. RenderFragments: Use them to pass HTML into components (like slots).
  2. Generics (@typeparam): Use them to create one component for multiple data types (Lists, Grids).
  3. DynamicComponent: Use it to load components based on runtime logic (CMS, Dashboards).
  4. ShouldRender: Use it to tell Blazor to ignore a component during the render cycle to save performance.

You are no longer just a Blazor coder. You are a Blazor Architect. Go forth and build scalable UIs! πŸ—οΈ


πŸ”— Useful References

Challenge

Challenge: Build a Dynamic and Performant Blazor Dashboard

Your task is to build a flexible dashboard system by implementing three components. This will test your knowledge of generic components, render fragments, dynamic rendering, and performance optimization.

1. Create a Generic and Reusable DataGrid<TItem> Component:

  • This component must be generic and accept any item type using the @typeparam directive.
  • It must define a parameter [Parameter] public IEnumerable<TItem> Items { get; set; } to receive data.
  • It must expose three RenderFragment slots for maximum flexibility:
    • [Parameter] public RenderFragment GridHeader { get; set; }
    • [Parameter] public RenderFragment<TItem> RowTemplate { get; set; }
    • [Parameter] public RenderFragment GridFooter { get; set; }
  • The component's markup should render the GridHeader, then iterate through the Items collection rendering the RowTemplate for each item, and finally render the GridFooter.

2. Create a Performance-Optimized StaticReportComponent:

  • This component will simulate a computationally expensive or static part of the UI.
  • It must accept a single string parameter: [Parameter] public string ReportId { get; set; }.
  • You must override the ShouldRender() lifecycle method.
  • Implement logic within ShouldRender() so that the component only re-renders if the value of the ReportId parameter has changed since the last render. You will need to store the previous ReportId value to perform this check.

3. Implement the DashboardHost.razor Page:

  • This component will act as the main container for your dynamic dashboard.
  • In the @code block, you will find pre-defined lists of User and Product objects, as well as a counter logic.
  • Use the built-in <DynamicComponent> to render different components based on user selection.
  • Create a Type property to hold the type of the component to be rendered, and a Dictionary<string, object> to hold its parameters.
  • Add three buttons:
    • "Load User Grid": Sets the DynamicComponent to render your DataGrid<User>, passing the user list and corresponding RenderFragment templates for its header, rows, and footer.
    • "Load Product Grid": Sets the DynamicComponent to render your DataGrid<Product>, passing the product list and its templates.
    • "Load Static Report": Sets the DynamicComponent to render your StaticReportComponent with a hardcoded ReportId.
  • Include a button that increments a counter on the DashboardHost page. This is to verify that your StaticReportComponent does not re-render unnecessarily when the parent's state changes.

Expected result

When your code is complete, the DashboardHost component should function as follows:

  1. Clicking the "Load User Grid" button should dynamically render the DataGrid component. It should display a header, two rows with user data (Name and Email), and a footer, all defined within the DashboardHost component's RenderFragments.
  2. Clicking the "Load Product Grid" button should dynamically render the same DataGrid component, but this time displaying product data (SKU, Name, and Price) using different RenderFragment templates.
  3. Clicking the "Load Static Report" button should render the StaticReportComponent. Note the time it was generated.
  4. After the static report is loaded, clicking the "Increment Parent Counter" button should NOT change the "Report Generated At" timestamp inside the StaticReportComponent. This confirms your ShouldRender() override is working correctly by preventing the child from re-rendering when the parent's state changes.
  5. Switching between the different views should be seamless, with the DynamicComponent correctly rendering the selected component and its associated parameters.
razor

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.