Blazor WASM Virtualization
blazor
27 Articles
In this article, let's learn about Virtualization
and how to use Virtualize
component to load huge data in Blazor WASM application.
Note: If you have not done so already, I recommend you read the article on Blazor WASM App Settings.
Table of Contents
- Why Virtualization?
- When Virtualization?
- Without Virtualization
- With Virtualization
- Virtualize Component
- Item provider delegate
- Placeholder
- Item Size
- Overscan count
- Statechanges
- Summary
Why Virtualization?
Loading a large dataset or displaying data
in a grid is a more common way to list data in many applications.
Virtualization
is a technique for limiting UI rendering to just the parts that are currently visible in UI.
This will improve the rendering performance and gives better user experience. For example, virtualization is helpful when the app must render a long list
of items and only a subset of items is required to be visible at any given time.
When Virtualization?
Use the Virtualize
component when:
- Rendering a set of data
items in a loop
. For example, loading Recommended Content in I ❤️ .NET - Most of the
items aren't visible due to scrolling
. - The rendered
items are the same size
.
When the user scrolls to a certain point in the Virtualize
component's list of items, the component
calculates the visible items to show. Unseen items aren't rendered.
Without Virtualization
Without virtualization, a typical list data might use a C# foreach
loop to render each item in a list.
In the following example:
tableOfContents.Contents
is a collection of contents.- The
VirtualizationContent
displays details about each content. -
The
@key directive attribute
preserves the relationship of eachVirtualizationContent
component to its rendered content by the content's ContentId.
Code Sample - Without Virtualization
Demo - Without Virtualization Demo
To demonstrate how list renders without virtualization, let's create a list of contents using foreach
loop.
Types of Clients in SignalR
Abdul Rahman
Improving performance and memory use while accessing APIs using HTTPClient in dotnet
Abdul Rahman
Fundamentals of SignalR in .Net
Abdul Rahman
Blazor WASM Publishing to GitHub Pages
Abdul Rahman
Blazor WASM Publishing to IIS
Abdul Rahman
Blazor WASM Event Handling And Event Arguments
Abdul Rahman
Blazor WASM Pre Rendering
Abdul Rahman
Generate PDF Report using Quest PDF in .NET
Abdul Rahman
OWASP - Secure your dotnet app by scanning for vulnerable nuget dependencies in CI pipelines
Abdul Rahman
Blazor WASM Dynamic Component
Abdul Rahman
Generate Excel Report using Closed XML in .NET
Abdul Rahman
Blazor WASM Communication Between Components
Abdul Rahman
Creational Design Pattern - Builder
Abdul Rahman
Structural Design Pattern - Facade
Abdul Rahman
Implementing Caching using Decorator Pattern in ASP.NET WEB API
Abdul Rahman
Structural Design Pattern - Decorator
Abdul Rahman
Blazor WASM App Settings
Abdul Rahman
Blazor WASM Virtualization
Abdul Rahman
Blazor WASM Javascript Interop and Isolation
Abdul Rahman
Blazor WASM Exception Handling and Error Boundary
Abdul Rahman
Blazor WASM Lazy Loading
Abdul Rahman
Structured Logging with Serilog in ASP.NET WEB API
Abdul Rahman
Using Docker Test Containers in Functional Testing in ASP.NET WEB API
Abdul Rahman
Global Exception Handling in ASP.NET WEB API
Abdul Rahman
Fitness Test using Net Arch Test in ASP.NET WEB API
Abdul Rahman
Request Endpoint Response (REPR) pattern in ASP.NET WEB API
Abdul Rahman
Using Hot Keys in Blazor WASM
Abdul Rahman
Prevent image leech by dynamically streaming image in Blazor WASM
Abdul Rahman
Improve performance by dynamically loading image in Blazor WASM
Abdul Rahman
Blazor WASM Error Logging
Abdul Rahman
Unit Testing HTTPClient in dotnet
Abdul Rahman
Extending HTTPClient with Custom Http Message Handlers in dotnet
Abdul Rahman
Working with API that supports remote streaming using HTTPClient in dotnet
Abdul Rahman
Save bandwidth with Compression when sending and reading data using HTTPClient in dotnet
Abdul Rahman
Free up resources with Cancellation while accessing APIs using HTTPClient in dotnet
Abdul Rahman
Unit Testing Hosted Services in ASP.NET WEB API
Abdul Rahman
Configuring Authentication in Functional testing in ASP.NET WEB API
Abdul Rahman
Using WireMock.NET in Functional testing in ASP.NET WEB API
Abdul Rahman
Faking Dependencies in Functional testing in ASP.NET WEB API
Abdul Rahman
Functional testing your ASP.NET WEB API
Abdul Rahman
Perform Background Workloads in Hosted Service using Channels in ASP.NET Web API
Abdul Rahman
Printing barcode to label printer from Blazor WASM
Abdul Rahman
How to generate barcode in Blazor WASM
Abdul Rahman
Unit Testing Controllers in ASP.NET Web API
Abdul Rahman
Unit Testing Service Registrations in ASP.NET Web API
Abdul Rahman
Unit Testing Middlewares in ASP.NET Web API
Abdul Rahman
Unit Testing Filters in ASP.NET Web API
Abdul Rahman
Blazor WASM Publishing to AWS Amplify
Abdul Rahman
Dependency Inversion Principle in SOLID
Abdul Rahman
Interface Segregation Principle in SOLID
Abdul Rahman
Liskov Substitution Principle in SOLID
Abdul Rahman
Open Closed Principle in SOLID
Abdul Rahman
Single Responsibility Principle in SOLID
Abdul Rahman
Convert HTML to PDF Report in .NET
Abdul Rahman
SOLID Principles Introduction
Abdul Rahman
Blazor WASM Dockerizing
Abdul Rahman
Creational Design Pattern - Singleton
Abdul Rahman
Design Pattern Introduction
Abdul Rahman
Understanding LINQ Deferred, Immediate, Streaming and Non-Streaming Executions
Abdul Rahman
Using LINQ For Each to Iterate Collections
Abdul Rahman
Using LINQ Count Min Max Average and Sum to Aggregate data
Abdul Rahman
Using LINQ Group By to group data
Abdul Rahman
Simulating Left Outer Join using LINQ
Abdul Rahman
Dependency Injection Lifetimes in .NET
Abdul Rahman
Using LINQ Group Join to combine data
Abdul Rahman
Using LINQ Join to combine data
Abdul Rahman
Using LINQ Concat to combine data
Abdul Rahman
Using LINQ Union to combine data
Abdul Rahman
Using LINQ Intersect to Find Common data
Abdul Rahman
Using LINQ Except to Find Difference in data
Abdul Rahman
Using LINQ Sequence Equal to Find Equality of data
Abdul Rahman
Using LINQ Contains to Check Data
Abdul Rahman
Using LINQ Any to Find Type of Data
Abdul Rahman
Using LINQ All to Find Type of Data
Abdul Rahman
Using LINQ Chunk to Split Data
Abdul Rahman
Using LINQ Distinct to Select Unique Data
Abdul Rahman
Using LINQ Skip to Select Specific Data
Abdul Rahman
Blazor WASM Styles and CSS Isolation
Abdul Rahman
Using LINQ Take to Select Specific Data
Abdul Rahman
Using LINQ Single to Select Single Data
Abdul Rahman
Using LINQ Last to Select Single Data
Abdul Rahman
Using LINQ First to Select Single Data
Abdul Rahman
Profiling Web API with Mini Profiler
Abdul Rahman
Python Dynamic Interop with Dotnet
Abdul Rahman
Using LINQ Where to Filter Data
Abdul Rahman
Using LINQ OrderBy to Sort Data
Abdul Rahman
Using LINQ to Select and Project Data
Abdul Rahman
LINQ Introduction
Abdul Rahman
Introducing Dependency Injection in .NET
Abdul Rahman
Types of Middleware in ASP.NET
Abdul Rahman
Introducing Middleware in ASP.NET
Abdul Rahman
Blazor WASM Forms Validation
Abdul Rahman
Blazor WASM Forms
Abdul Rahman
OOPS Abstraction
Abdul Rahman
Blazor WASM Controlling Head Content
Abdul Rahman
OOPS Encapsulation
Abdul Rahman
Blazor WASM Data Binding
Abdul Rahman
Blazor WASM Components
Abdul Rahman
Implementing TDD in C# .Net
Abdul Rahman
Introducing TDD in C# .Net
Abdul Rahman
Blazor WASM Introduction
Abdul Rahman
Blazor - SPA from ASP.NET Family
Abdul Rahman
Importance of Status Code in Web API
Abdul Rahman
Blazor WASM Dark Theme and Light Theme
Abdul Rahman
With Virtualization
If the collection contains thousands of contents, rendering the contents takes a long time and users experience a noticeable UI lag. Most of the
contents aren't seen because they fall outside of the height of the <div>
element.
Instead of rendering the entire list of contents at once, replace the foreach
loop in the preceding example
with the Virtualize
component:
-
Specify
tableOfContents.Contents
as a fixed item source toVirtualize<TItem>.Items
. Only the currently visible contents are rendered by theVirtualize
component. -
Specify a context for each content with the
Context
parameter. In the following example,content
is used as the context, which provides access to each content's details.
Code Sample - With Virtualization
Demo - With Virtualization Demo
To demonstrate how list renders with virtualization, let's create a list of contents using Virtualize
Component.
If a context isn't specified with the Context
parameter, use the value of
context
in the item content template to access each contents's details:
Virtualize Component
The Virtualize
component:
Calculates the number of items to render
based on the height of the container and the size of the rendered items.Recalculates and rerenders the items
as the user scrolls.Only fetches the slice of records from an external API that correspond to the current visible region
, instead of downloading all of the data from the collection.
The item content for the Virtualize
component can include:
Plain HTML and Razor code
, as the preceding example shows.- One or more
Razor components
. - A mix of
HTML/Razor and Razor components
.
Item provider delegate
If you don't want to load all of the items into memory, you can specify an items provider delegate method to the component's
Virtualize<TItem>.ItemsProvider
parameter that asynchronously retrieves the requested items on demand.
In the following example, the LoadContents
method provides the items to the
Virtualize
component:
Code Sample - Item Provider Delegate
The items provider receives an ItemsProviderRequest
, which specifies the required number of items starting
at a specific start index. The items provider then retrieves the requested items from a database or other service and returns them as an
ItemsProviderResult<TItem>
along with a count of the total items. The items provider can choose to
retrieve the items with each request or cache them so that they're readily available.
A Virtualize
component can only accept one item source from its parameters, so don't attempt
to simultaneously use an items provider and assign a collection to Items. If both are assigned, an
InvalidOperationException
is thrown when the component's parameters are set at runtime.
Placeholder
Because requesting items from a remote data source might take some time, you have the option to render a placeholder
with item content:
Code Sample - Virtualization with Placeholder
-
Use a
Placeholder (<Placeholder>...</Placeholder>)
to display content until the item data is available. - Use
Virtualize<TItem>.ItemContent
to set the item template for the list.
Item size
The height of each item in pixels can be set with Virtualize<TItem>.ItemSize
(default: 50). By default,
the Virtualize
component measures the rendering size (height) of individual items after the initial render
occurs. Use ItemSize
to provide an exact item size in advance to assist with accurate initial render performance
and to ensure the correct scroll position for page reloads. If the default ItemSize causes some items to render outside of the currently visible view,
a second re-render is triggered. To correctly maintain the browser's scroll position in a virtualized list, the initial render must be correct. If not,
users might view the wrong items. The following example changes the height of each item from the default of 50 pixels to 25 pixels:
Code Sample - Virtualization with Item Size
Overscan count
Virtualize<TItem>.OverscanCount
determines and controls how many additional items are rendered before
and after the visible region. This setting helps to reduce the frequency of rendering during scrolling. However, higher values result in more
elements rendered in the page (default: 3). The following example changes the overscan count from the default of three items to four items:
Code Sample - Virtualization with Overscan Count
Statechanges
When making changes to items rendered by the Virtualize
component, call
StateHasChanged
to force re-evaluation and rerendering of the component.
Summary
In this article, we learn't how to use Virtualize
component to load huge data
without compromising on performance and user experience. We also learn't about Item provider delegate
,
Placeholder
, Item size
and Overscan count
.
The live in browser demo should have helped you to see what is happening in realtime while you scroll.