State Management in Blazor Web Assembly with ASP.NET 6.0
Table of Contents
For an advanced and more comprehensive discussion on State Management in Blazor, go here
What is State Management ?
The web is by itself stateless, meaning that the rendered user data on the browsers will get lost. It does not keep track of configuration settings, transaction information or any other data for the next session.
Another way to understand this is when a user closes and re-opens their browser or reloads the page, user state held in the browser’s memory is lost.
So we need to use some techniques so that the browser’s memory is kept intact despite refreshing or closing the browser. This is called State Management
How State Management in Blazor Web Assembly is done ?
The browser’s memory holds the User state created in a Blazor WebAssembly app.
Examples of user state held in browser memory include:
- The values of fields and properties in component instances.
- The hierarchy of component instances and their most recent render output in the rendered UI.
- Data held in dependency injection (DI) service instances.
- Values set through JavaScript interop calls.
State Persistence across Browser Sessions
The idea is to maintain state across sessions where users are creating data actively, not merely reading the already existing data.
State persistence isn’t automatic. Hence steps must be taken when developing the app to implement stateful data persistence. Some other storage location than the browser’s memory must be used to preserve state across browser sessions.
Data persistence is generally required for high value data that can’t or shouldn’t be lost for the sake of the business. Persisting state saves time and aids in commercial activitoes. This is topped up by presenting a good user experience which is seamless to the eyes. A couple of example use cases where State Management is essential are:
- Shopping Carts: When a user shops online using an e-commerce site, the maintenance of shopping cart state is important as it represents a potential revenue. If a user loses their shopping cart by losing their state, they may end up purchasing fewer products or no products at all as they return to the site later.
- Multi-step Web Form Wizards: A user loses state if they navigate away from the form and return later for a multi-step form with wizard. So if a mechanism is not available to maintain that user state, they will feel pain (as it is time-consuming) to re-enter the data for several steps of that web form.
Location to persist state
There are the following common locations for persisting state:
- In memory state container service
- Browser storage
- Server-side storage
- URL
In this post, we shall be using the In memory state container service and build a project to demonstrate the same using ASP.NET 6.0

As shown in Fig 1, the global state object must be defined.
This object must define property (or properties) that will be used to maintain the state of data to be shared across the components. This object also defines an event.
The event is raised when the sender component modifies its state and updates the previous state of the value – from global state container object, to new state. The public method in this object will be accessed by the sender component to send the new state to the global object. Once the state is changed in the global object, the other receiver component can subscribe to the global state object and receive the modified state.
YouTube Version
Available at this location
Implementation of State Management in Blazor
Open Visual Studio 2022 as below Fig 2 and Create a new project dialog opens. Select Blazor WebAssembly App and Next:

On Configure your new project give it any suitable name and Next (Fig 3)

On the Additional Information page keep the defaults as Fig 4 and hit Create

Add a Models folder to the root of the project and Add these model classes:
Customer class in a Customer.cs file and paste the following code (overwrite the default code):
namespace Blazor_StateManagement.Models;
public class Customer
{
public int CustomerId { get; set; }
public string CustomerName { get; set; }
}
public class Customers : List<Customer>
{
public Customers()
{
Add(new Customer() { CustomerId = 1, CustomerName = "John Roddick" });
Add(new Customer() { CustomerId = 2, CustomerName = "Harold William" });
}
}
Also create an Order class in a separate Order.cs file and overwrite the code with the following:
namespace Blazor_StateManagement.Models;
public class Order
{
public int OrderId { get; set; }
public string Description { get; set; }
public int CustomerId { get; set; }
}
public class Orders : List<Order>
{
public Orders()
{
Add(new Order() { OrderId = 101, Description = "Order1", CustomerId = 1 });
Add(new Order() { OrderId = 102, Description = "Order2", CustomerId = 2 });
Add(new Order() { OrderId = 103, Description = "Order3", CustomerId = 1 });
Add(new Order() { OrderId = 104, Description = "Order4", CustomerId = 2 });
}
}
Create the State Container
To maintain the state of the data across sender to receiver components, we need to create a global state container service class as shown in Fig. 1. Now create a folder named StateService and add a file StateContainerService.cs. Paste the following code to replace the existing code in the StateContainerService class:
namespace Blazor_StateManagement.StateService;
public class StateContainerService
{
///<summary>
///The state property with initial value
///</summary>
public int Value { get; set; }
///<summary>
///The event will be raised for state changed
///</summary>
public event Action OnStateChange;
///<summary>
///This method will be accessed by the sender component
///to update the state
///</summary>
public void SetValue(int value)
{
Value = value;
NotifyStateChanged();
}
private void NotifyStateChanged()=> OnStateChange?.Invoke();
}
These are important observations to be made as per the listing above:
1. ‘Value’ is the state property declared as integer with default value as 0. This value will be changed by the sender component.
2. ‘OnStateChange’ is an event. This event will be raised when the state is changed.
3. ‘NotifyStateChanged()’ is the method that will be used to raise the OnStateChange event when the state is changed.
4. ‘SetValue()’ method will be invoked by the sender component to modify the old state to the new state. Once the state is changed then the ‘NotifyStateChanged()’ method will be called to raise the state changed event.
Register the State Container
Add the following code in the Program.cs file just above the last line
builder.Services.AddSingleton<StateContainerService>();
Create the Razor Components
Let’s now create the Razor Components (Sender Component => Customer and Receiver Component => Order)
Right click the Pages folder and Click Add => Razor Component (Fig. 5)

On the Add New Item dialog, give a name as follows (Fig 6)

Add the following code in the CustomerSenderComponent to overwrite the existing code:
@page "/customersendercomponent"
@using Blazor_StateManagement.Models;
@inject StateService.StateContainerService stateService;
@implements IDisposable
@inject NavigationManager uriHelper;
<h3>Customer Sender Component</h3>
<div class="container">
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Customer Id</th>
<th>Customer Name</th>
</tr>
</thead>
<tbody>
@foreach (var cust in customers)
{
<tr>
<td>@cust.CustomerId</td>
<td>@cust.CustomerName</td>
<td>
<input type="button" @onclick="@(()=>SelectedCustomer(cust.CustomerId))" value="Select" />
</td>
</tr>
}
</tbody>
</table>
</div>
@code {
private Customer customer;
private Customers customers;
protected override void OnInitialized()
{
customer = new Customer();
customers = new Customers();
stateService.OnStateChange += StateHasChanged;
}
void SelectedCustomer(int custid)
{
stateService.SetValue(custid);
uriHelper.NavigateTo("/orderreceivercomponent");
}
public void Dispose()
{
stateService.OnStateChange -= StateHasChanged;
}
}
Following the steps above (Fig 5 & Fig 6) create one more Razor component and name it OrderReceiverComponent.
Paste the following code in the OrderReceiverComponent to over-write the default existing code:
@page "/orderreceivercomponent"
@using Blazor_StateManagement.Models;
@inject StateService.StateContainerService stateService;
@implements IDisposable
@inject NavigationManager uriHelper;
<h3>Order Receiver Component</h3>
<div class="container">
<h2>The Received Customer Id is = @CustId</h2>
<table class="table table-bordered table-striped">
<thead>
<tr>
<th>Order Id</th>
<th>Order Description</th>
<th>Customer Id</th>
</tr>
</thead>
<tbody>
@foreach (var ord in filteredOrders)
{
<tr>
<td>@ord.OrderId</td>
<td>@ord.Description</td>
<td>@ord.CustomerId</td>
</tr>
}
</tbody>
</table>
</div>
@code {
private Orders orders;
private List<Order> filteredOrders;
private int CustId;
protected override void OnInitialized()
{
orders = new Orders();
filteredOrders = new List<Order>();
CustId = stateService.Value;
if (CustId == 0)
{
filteredOrders = orders;
}
else
{
filteredOrders = orders.Where(o => o.CustomerId == CustId).ToList();
}
}
public void Dispose()
{
stateService.OnStateChange -= StateHasChanged;
}
}
Like the CustomerSenderComponent, the OrderReceiverComponent is also injected by the StateContainerService. The OnInitialized() method accesses the modified state from the StateContainerService class using its Value property. Once the modified state is received, the OrderReceiverComponent filters Order data based on the Customer data received from the State. The OrderReceiverComponent renders the orders based on the CustomerId.
Create the Navigation Menu (for Razor Components)
Open Shared/NavMenu.razor and add the navigation for the two components by pasting the following markup
<div class="nav-item px-3">
<NavLink class="nav-link" href="orderreceivercomponent">
<span class="oi oi-list-rich" aria-hidden="true"></span> Order
</NavLink>
</div>
between <nav class = “@NavMenuCssClass” @onclick = “ToggleNavMenu”> </nav>
Run the Application
Run the application and the browser renders the following view on Clicking the Customer menu

Now click any of the Select buttons in the Customer Sender Component. You’ll get the following screen (for the Order Receiver Component)

Fig. 9 (Developer Tools),
Open the Developer Tab (F12) and then the Application tab, select Cache Storage. This shows .NET assemblies loaded in the browser. In this tab in the ‘Filter by Path’ textbox, enter Blazor_StateManagement, this will the show the current application assembly loaded in the browser as shown in Fig. 9:

The application assembly also contains the StateContainerService class to maintain state in the browser. Instead of using any of the browser resources, state is maintained by the application itself and it can be easily shared across all the components.
Conclusion
Conclusion:
State Management is one of the much-needed features in modern web applications. The advantage of it is that since the data is managed in the browser, frequent postbacks to the server can be avoided. In Blazor applications (Web Assembly project), we can easily implement State Management using Global State Container Object because the application with its dependencies is loaded and executed in the browser.
Follow Me Here