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:
<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)
<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)
<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)
<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
<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."
@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!
<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
Contextattribute defaults to the namecontextif you don't specify it. But renaming it touserorproductmakes your code much more readable. Otherwise, you end up with nested loops ofcontext.Nameinsidecontext.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":
@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
@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: AcceptsTheme.StockWidget.razor: AcceptsRefreshRate.
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
DynamicComponentdoes 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)
<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.
@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
ShouldRenderwhen you actually notice a lag in the UI or look at the profiler and see excessive rendering events.
π Summary Checklist
- RenderFragments: Use them to pass HTML into components (like slots).
- Generics (
@typeparam): Use them to create one component for multiple data types (Lists, Grids). - DynamicComponent: Use it to load components based on runtime logic (CMS, Dashboards).
- 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
@typeparamdirective. - It must define a parameter
[Parameter] public IEnumerable<TItem> Items { get; set; }to receive data. - It must expose three
RenderFragmentslots 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 theItemscollection rendering theRowTemplatefor each item, and finally render theGridFooter.
2. Create a Performance-Optimized StaticReportComponent:
- This component will simulate a computationally expensive or static part of the UI.
- It must accept a single
stringparameter:[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 theReportIdparameter has changed since the last render. You will need to store the previousReportIdvalue to perform this check.
3. Implement the DashboardHost.razor Page:
- This component will act as the main container for your dynamic dashboard.
- In the
@codeblock, you will find pre-defined lists ofUserandProductobjects, as well as a counter logic. - Use the built-in
<DynamicComponent>to render different components based on user selection. - Create a
Typeproperty to hold the type of the component to be rendered, and aDictionary<string, object>to hold its parameters. - Add three buttons:
- "Load User Grid": Sets the
DynamicComponentto render yourDataGrid<User>, passing the user list and correspondingRenderFragmenttemplates for its header, rows, and footer. - "Load Product Grid": Sets the
DynamicComponentto render yourDataGrid<Product>, passing the product list and its templates. - "Load Static Report": Sets the
DynamicComponentto render yourStaticReportComponentwith a hardcodedReportId.
- "Load User Grid": Sets the
- Include a button that increments a counter on the
DashboardHostpage. This is to verify that yourStaticReportComponentdoes not re-render unnecessarily when the parent's state changes.
Expected result
When your code is complete, the DashboardHost component should function as follows:
- Clicking the "Load User Grid" button should dynamically render the
DataGridcomponent. It should display a header, two rows with user data (Name and Email), and a footer, all defined within theDashboardHostcomponent'sRenderFragments. - Clicking the "Load Product Grid" button should dynamically render the same
DataGridcomponent, but this time displaying product data (SKU, Name, and Price) using differentRenderFragmenttemplates. - Clicking the "Load Static Report" button should render the
StaticReportComponent. Note the time it was generated. - 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 yourShouldRender()override is working correctly by preventing the child from re-rendering when the parent's state changes. - Switching between the different views should be seamless, with the
DynamicComponentcorrectly rendering the selected component and its associated parameters.