In the SharpRune app for iPhone and iPad, tap Run in Preview: the app compiles the Razor components on the device and runs the project on .NET 9. On a computer, download the project and run it with the .NET 9 SDK. The separate C# companion practice below runs in this browser.
Cascading value or state container
CascadingValue: the currency- Any component inside it can receive the value
Apprenders a newCurrency; receivers render- Changing a property inside it notifies no one
CartState service: the cart- A singleton injected by
ShopandCartBadge - Every change method raises
OnChange - Subscribers render through
InvokeAsync - Unsubscribe in
Dispose, or the listener stays
A cascade reaches every [CascadingParameter] below it; a service keeps unrelated components in sync. Subscribers call InvokeAsync(StateHasChanged), so timer changes render safely.
When parameters are not enough
A [Parameter] moves data one level down, from a parent to the child it renders. An EventCallback moves a notification one level up. That covers most components. It breaks down in two situations. The first is a value that many components at different depths need, such as a theme, the signed-in user or a currency. Passing it as a parameter through every layer forces components that never use it to carry it. The second is two components with no parent and child link, such as a badge in the header and a list on the page. Neither renders the other, so neither can pass parameters to the other.
Blazor's answer to the first is a cascading value. The usual answer to the second is a state container: a service that both components inject. The State Lab project uses both, and each solves a different problem.
How cascading values work
CascadingValue is a component. Everything rendered inside its child content can receive its Value. A component asks for it with a property marked [CascadingParameter]. Blazor looks up the tree for the closest CascadingValue whose value type fits the property type. If several values have the same type, give them a Name and use [CascadingParameter(Name = "...")].
Each time the component that renders the CascadingValue renders again, the CascadingValue checks whether the value may have changed. For known immutable types such as int, string or decimal it compares the values. Any other object counts as possibly changed, so Blazor re-renders every component that receives it. In the project, App.razor builds the Currency from currencyCode. When you pick USD, App renders again, the value is a different record, and both CartBadge and the Shop page render with dollar prices.
Changing a property inside the cascaded object does not notify anyone, because the owner did not render. Replace the object, as the project does with records, or render the owner again. If a value never changes, set IsFixed="true" so Blazor skips the change tracking. Since .NET 8 you can also register a cascading value for the whole app in Program.cs with AddCascadingValue.
The state container pattern
A state container is an ordinary C# class. CartState keeps a private list, exposes it as IReadOnlyList, and changes it only through methods: Add, Remove, Clear and ScheduleGift. Each method ends by raising OnChange. Because every change goes through a method, no change can skip the event.
Program.cs registers CartState as a singleton, and each component gets it with @inject. In WebAssembly, the app runs in one browser tab for one user, and scoped services behave like singletons. In Blazor Server, a singleton would be shared by every user of the server, so per-user state there belongs in a scoped service.
The state lives in memory. Reload the page and the cart is empty again. Keeping it requires storage, for example localStorage through JavaScript interop, or a server.
Why InvokeAsync(StateHasChanged)
The renderer runs its work on a synchronization context, sometimes called the dispatcher. Blazor event handlers and lifecycle methods already run there. Code started from elsewhere does not: a System.Threading.Timer callback, the rest of a method after ConfigureAwait(false), or an event raised by a service on another thread. In Blazor Server, calling StateHasChanged from such code throws an exception that says the current thread is not associated with the Dispatcher.
Today's WebAssembly runtime runs .NET on one thread, so the direct call often works there. Code that depends on that breaks when you move it to Server or to a multithreaded runtime. ComponentBase.InvokeAsync queues the call onto the renderer's context and returns a Task. The handlers in the project discard that task with _ =, which is fine for a render request. The gift in CartState arrives from a timer callback, which is exactly this case.
Subscribing and unsubscribing
An event holds a strong reference to each subscriber. A singleton CartState lives as long as the app, so every component that subscribes and never unsubscribes stays in memory, and its handler keeps running after the component left the screen. StateHasChanged on a disposed component does nothing, but the handler still runs. The companion shows this: the forgotten listener counts a render after Dispose, and the subscriber count does not go down.
Subscribe in OnInitialized, which runs once per component instance. OnParametersSet runs many times, and subscribing there adds the same handler again and again. Use a named method such as CartChanged, because -= must receive the same delegate that += added. An anonymous lambda written twice gives two different delegates, and the -= does nothing. Add @implements IDisposable and unsubscribe in Dispose.
Trace the State Lab project
When the app starts, App renders the CascadingValue with Currency.Euro, the header with CartBadge, and the Router with the Shop page. Both components subscribe to OnChange. Tap Add on the Notebook. CartState.Add updates the list and raises OnChange. Both handlers call InvokeAsync(StateHasChanged), so the badge and the page render. The page would also render because of its own click, but the badge has no other way to learn about it.
Tap Empty in the badge. Clear raises OnChange, and the page renders its empty cart. Without its subscription, the page would keep showing old lines until something else made it render. Tap Send me a free gift. ScheduleGift starts a timer and raises OnChange, so the button turns disabled at once. Two seconds later the timer callback calls Add, outside any Blazor event, and the subscriptions bring both components up to date.
The companion repeats the subscription logic without Blazor. Three changes give three renders for each listener and two subscribers. After the page listener is disposed, one subscriber remains and only the badge counts the next change.
Practice and review
Remove the subscription from Shop.razor, run the app, and tap Empty in the badge. Predict what the page shows before you look, then put the subscription back. Add a third subscriber, a small CartFooter component at the bottom of the page that shows the number of different products. Give the CascadingValue the name Currency and update both parameters to match. Add a cascading Theme with IsFixed="true" and use it for the badge color. Finally, save the cart lines to localStorage with the JavaScript interop from the previous lesson and load them in OnAfterRenderAsync.
- A
CascadingValuegives a value to every component inside it; receivers declare[CascadingParameter]. - Replace a cascaded object to notify receivers; changing its properties notifies no one.
- A state container holds shared data and raises an event after every change.
- Subscribe once in
OnInitialized, unsubscribe with the same named method inDispose. - Call
InvokeAsync(StateHasChanged) from event handlers that may run outside the renderer.
Sharing state across components — Blazor WebAssembly project
Run the project
- Tap Run in Preview. SharpRune copies these files into a new project, compiles the Razor components on this device and opens the app in Preview.
- Add a few products, switch the currency in the header, then tap Empty on the cart badge and watch the cart list on the page.
- Tap Send me a free gift and wait two seconds. The timer in CartState adds a sticker, and the badge and the cart list both update.
- Change a .razor file and tap Run again to rebuild.
- On a computer: install the .NET 9 SDK, save the files with their folders, and run dotnet run in that folder.
Project files
StateLab.csproj
Download file ↗<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">
<PropertyGroup>
<TargetFramework>net9.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<AssemblyName>StateLab</AssemblyName>
<RootNamespace>StateLab</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="9.0.4" />
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="9.0.4" PrivateAssets="all" />
</ItemGroup>
</Project>
Program.cs
Download file ↗using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using StateLab;
using StateLab.Services;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");
// One cart for the whole app. Every component that injects CartState gets this same object.
builder.Services.AddSingleton<CartState>();
await builder.Build().RunAsync();
App.razor
Download file ↗@* The root component. CascadingValue hands the chosen currency to every component
inside it, including the pages the Router creates, without any [Parameter]. *@
<CascadingValue Value="currency">
<header class="bar">
<span class="brand">State Lab</span>
<label class="currency">
<span>Currency</span>
<select @bind="currencyCode">
<option value="EUR">EUR</option>
<option value="USD">USD</option>
</select>
</label>
<CartBadge />
</header>
<main>
<Router AppAssembly="@typeof(App).Assembly">
<Found Context="routeData">
<RouteView RouteData="@routeData" />
<FocusOnNavigate RouteData="@routeData" Selector="h1" />
</Found>
<NotFound>
<PageTitle>Not found</PageTitle>
<h1>Not found</h1>
<p>There is no page at this address.</p>
</NotFound>
</Router>
</main>
</CascadingValue>
@code {
private string currencyCode = "EUR";
// A new value here re-renders every component that has a [CascadingParameter] Currency.
private Currency currency => currencyCode == "USD" ? Currency.Dollar : Currency.Euro;
}
_Imports.razor
Download file ↗@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using StateLab
@using StateLab.Components
@using StateLab.Services
Components/CartBadge.razor
Download file ↗@* Lives in the header. It is neither parent nor child of the shop page,
so it hears about cart changes through CartState.OnChange. *@
@implements IDisposable
@inject CartState Cart
<span class="badge" role="status">
Cart: @Cart.Count · @Currency.Format(Cart.TotalEur)
<button class="empty" @onclick="Cart.Clear" disabled="@(Cart.Count == 0)">Empty</button>
</span>
@code {
// Filled by the CascadingValue in App.razor.
[CascadingParameter] public Currency Currency { get; set; } = Currency.Euro;
protected override void OnInitialized() => Cart.OnChange += CartChanged;
// The event may fire outside Blazor's own event handling (here: a timer).
// InvokeAsync runs StateHasChanged on the renderer's synchronization context.
private void CartChanged() => _ = InvokeAsync(StateHasChanged);
// Without this, the service would keep calling a component that is gone.
public void Dispose() => Cart.OnChange -= CartChanged;
}
Pages/Shop.razor
Download file ↗@page "/"
@implements IDisposable
@inject CartState Cart
<PageTitle>Shop</PageTitle>
<h1>Shop</h1>
<p class="muted">Prices use the currency picked in the header. This page and the header badge both listen to the same CartState.</p>
<ul class="products">
@foreach (var product in products)
{
<li>
<span class="name">@product.Name</span>
<span class="price">@Currency.Format(product.PriceEur)</span>
<button class="primary" @onclick="() => Cart.Add(product)">Add</button>
</li>
}
</ul>
<button @onclick="() => Cart.ScheduleGift(TimeSpan.FromSeconds(2))" disabled="@Cart.GiftPending">
@(Cart.GiftPending ? "Gift arrives in 2 seconds…" : "Send me a free gift")
</button>
<h2>Your cart</h2>
@if (Cart.Lines.Count == 0)
{
<p class="muted">The cart is empty.</p>
}
else
{
<ul class="lines">
@foreach (var line in Cart.Lines)
{
<li>
<span class="name">@line.Quantity × @line.Product.Name</span>
<span class="price">@Currency.Format(line.TotalEur)</span>
<button class="link" @onclick="() => Cart.Remove(line)">Remove</button>
</li>
}
</ul>
<p class="total">Total: @Currency.Format(Cart.TotalEur)</p>
}
@code {
// Filled by the CascadingValue in App.razor, like in CartBadge.
[CascadingParameter] public Currency Currency { get; set; } = Currency.Euro;
private readonly Product[] products =
[
new("Notebook", 4.50m),
new("Pencil set", 7.20m),
new("Desk lamp", 24.90m)
];
// Subscribe once, when the component starts.
protected override void OnInitialized() => Cart.OnChange += CartChanged;
// Needed for changes this page did not cause: the Empty button in the header and the gift timer.
private void CartChanged() => _ = InvokeAsync(StateHasChanged);
// Unsubscribe when the component leaves the screen.
public void Dispose() => Cart.OnChange -= CartChanged;
}
Services/CartState.cs
Download file ↗using System.Globalization;
namespace StateLab.Services;
public sealed record Product(string Name, decimal PriceEur);
public sealed record CartLine(Product Product, int Quantity)
{
public decimal TotalEur => Product.PriceEur * Quantity;
}
// The cascading value. Prices are stored in euros and converted for display.
public sealed record Currency(string Code, string Symbol, decimal PerEuro)
{
public static readonly Currency Euro = new("EUR", "€", 1.00m);
public static readonly Currency Dollar = new("USD", "$", 1.10m); // a fixed demo rate
public string Format(decimal euros) =>
Symbol + (euros * PerEuro).ToString("0.00", CultureInfo.InvariantCulture);
}
// A state container: it holds the data and raises OnChange after every change.
// It knows nothing about components; they subscribe to the event.
public sealed class CartState
{
private readonly List<CartLine> lines = [];
private Timer? giftTimer;
public event Action? OnChange;
public IReadOnlyList<CartLine> Lines => lines;
public int Count => lines.Sum(line => line.Quantity);
public decimal TotalEur => lines.Sum(line => line.TotalEur);
public bool GiftPending => giftTimer is not null;
public void Add(Product product)
{
var index = lines.FindIndex(line => line.Product == product);
if (index >= 0)
{
lines[index] = lines[index] with { Quantity = lines[index].Quantity + 1 };
}
else
{
lines.Add(new CartLine(product, 1));
}
NotifyStateChanged();
}
public void Remove(CartLine line)
{
lines.Remove(line);
NotifyStateChanged();
}
public void Clear()
{
lines.Clear();
NotifyStateChanged();
}
// Adds a gift later from a timer callback. The change does not come from a
// click in any component, like a message from a server would not.
public void ScheduleGift(TimeSpan delay)
{
if (giftTimer is not null) return;
giftTimer = new Timer(_ =>
{
giftTimer?.Dispose();
giftTimer = null;
Add(new Product("Sticker (gift)", 0m));
}, null, delay, Timeout.InfiniteTimeSpan);
NotifyStateChanged();
}
private void NotifyStateChanged() => OnChange?.Invoke();
}
wwwroot/index.html
Download file ↗<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>State Lab</title>
<base href="/" />
<link rel="stylesheet" href="css/app.css" />
<link rel="stylesheet" href="StateLab.styles.css" />
</head>
<body>
<div id="app">
<p class="loading">Starting .NET…</p>
</div>
<div id="blazor-error-ui">
An unhandled error has occurred.
<a href="." class="reload">Reload</a>
<span class="dismiss">✕</span>
</div>
<script src="_framework/blazor.webassembly.js"></script>
</body>
</html>
wwwroot/css/app.css
Download file ↗:root {
color-scheme: light dark;
--accent: #6b4eff;
--line: #d8d6e4;
--danger: #d32f2f;
--ok: #2e7d32;
}
body {
margin: 0;
font-family: -apple-system, system-ui, sans-serif;
line-height: 1.5;
}
a, button, input, label { touch-action: manipulation; }
select { touch-action: manipulation; }
.bar {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 8px 16px;
padding: 12px 16px;
background: #1f1b3a;
color: #fff;
}
.brand {
font-weight: 700;
margin-right: auto;
}
.bar nav {
display: flex;
gap: 4px;
}
.bar nav a {
color: #d9d4ff;
text-decoration: none;
padding: 6px 10px;
border-radius: 8px;
}
.bar nav a.active {
background: var(--accent);
color: #fff;
}
main {
padding: 20px 16px 40px;
max-width: 720px;
margin: 0 auto;
box-sizing: border-box;
}
h1 {
font-size: 1.8rem;
margin: 0 0 12px;
}
h1:focus {
outline: none;
}
h2 {
font-size: 1.15rem;
margin: 24px 0 8px;
}
.loading {
padding: 32px 16px;
color: #777;
}
.muted {
color: #777;
}
.row {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin: 12px 0;
}
input:not([type=checkbox]), select, textarea {
font: inherit;
color: inherit;
background: transparent;
padding: 8px 10px;
border: 1px solid var(--line);
border-radius: 8px;
min-width: 0;
box-sizing: border-box;
}
button {
font: inherit;
padding: 8px 14px;
border-radius: 8px;
border: 1px solid var(--line);
background: transparent;
color: inherit;
}
button.primary {
background: var(--accent);
border-color: var(--accent);
color: #fff;
}
button:disabled {
opacity: 0.45;
}
button.link {
border: none;
color: var(--accent);
padding: 4px 6px;
}
code {
font-size: 0.9em;
overflow-wrap: anywhere;
}
#blazor-error-ui {
display: none;
position: fixed;
bottom: 0;
left: 0;
right: 0;
padding: 12px 16px;
background: #ffe8a3;
color: #222;
}
.currency {
display: flex;
align-items: center;
gap: 6px;
font-size: 0.9rem;
}
.currency select {
padding: 4px 6px;
color: #fff;
border-color: #6d64a8;
}
.currency option {
color: #222;
}
.badge {
display: flex;
align-items: center;
gap: 8px;
padding: 4px 4px 4px 10px;
border-radius: 999px;
background: var(--accent);
font-size: 0.9rem;
font-weight: 600;
}
.badge .empty {
padding: 2px 10px;
border: none;
border-radius: 999px;
background: rgba(255, 255, 255, 0.2);
font-size: 0.85rem;
}
.products, .lines {
list-style: none;
padding: 0;
margin: 0 0 16px;
}
.products li, .lines li {
display: flex;
align-items: center;
gap: 10px;
padding: 10px 0;
border-bottom: 1px solid var(--line);
}
.name {
flex: 1;
}
.price {
font-variant-numeric: tabular-nums;
}
.total {
font-weight: 700;
}
Expected result
Adding products updates the header badge, for example 'Cart: 3 · €33.90', and the cart list on the page at the same time. Switching to USD changes every price on the page and in the badge: the Notebook goes from €4.50 to $4.95. Tapping Empty in the badge clears the cart list on the page. 'Send me a free gift' changes to 'Gift arrives in 2 seconds…' and is disabled; two seconds later '1 × Sticker (gift)' appears in the cart and the badge count goes up by one.
The project runs in the SharpRune app and with the .NET 9 SDK. Open C# practice runs the separate portable exercise.
C# companion practice
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
// The same CartState idea as Services/CartState.cs, with listeners that count their renders.
var cart = new CartState();
var badge = new Listener(cart);
var page = new Listener(cart);
var notebook = new Product("Notebook", 4.50m);
cart.Add(notebook);
cart.Add(notebook);
cart.Add(new Product("Desk lamp", 24.90m));
Console.WriteLine($"Cart: {cart.Count} items, {Currency.Euro.Format(cart.TotalEur)} or {Currency.Dollar.Format(cart.TotalEur)}");
foreach (var line in cart.Lines)
{
Console.WriteLine($" {line.Quantity} x {line.Product.Name}");
}
Console.WriteLine($"Renders: badge {badge.Renders}, page {page.Renders}, subscribers {cart.SubscriberCount}");
// The page leaves the screen and unsubscribes in Dispose.
page.Dispose();
cart.Clear();
Console.WriteLine($"After page.Dispose(): badge {badge.Renders}, page {page.Renders}, subscribers {cart.SubscriberCount}");
// A listener that never unsubscribes keeps reacting after it is gone.
var forgotten = new Listener(cart, unsubscribeOnDispose: false);
forgotten.Dispose();
cart.Add(notebook);
Console.WriteLine($"Forgotten listener rendered {forgotten.Renders} time(s) after Dispose; subscribers {cart.SubscriberCount}");
public sealed record Product(string Name, decimal PriceEur);
public sealed record CartLine(Product Product, int Quantity);
public sealed record Currency(string Code, string Symbol, decimal PerEuro)
{
public static readonly Currency Euro = new("EUR", "€", 1.00m);
public static readonly Currency Dollar = new("USD", "$", 1.10m);
public string Format(decimal euros) =>
Symbol + (euros * PerEuro).ToString("0.00", CultureInfo.InvariantCulture);
}
public sealed class CartState
{
private readonly List<CartLine> lines = [];
public event Action? OnChange;
public IReadOnlyList<CartLine> Lines => lines;
public int Count => lines.Sum(line => line.Quantity);
public decimal TotalEur => lines.Sum(line => line.Product.PriceEur * line.Quantity);
public int SubscriberCount => OnChange?.GetInvocationList().Length ?? 0;
public void Add(Product product)
{
var index = lines.FindIndex(line => line.Product == product);
if (index >= 0)
{
lines[index] = lines[index] with { Quantity = lines[index].Quantity + 1 };
}
else
{
lines.Add(new CartLine(product, 1));
}
OnChange?.Invoke();
}
public void Clear()
{
lines.Clear();
OnChange?.Invoke();
}
}
// Plays the part of a component: subscribe when created, unsubscribe in Dispose.
public sealed class Listener : IDisposable
{
private readonly CartState cart;
private readonly bool unsubscribeOnDispose;
public Listener(CartState cart, bool unsubscribeOnDispose = true)
{
this.cart = cart;
this.unsubscribeOnDispose = unsubscribeOnDispose;
cart.OnChange += Render;
}
public int Renders { get; private set; }
private void Render() => Renders++;
public void Dispose()
{
if (unsubscribeOnDispose)
{
cart.OnChange -= Render;
}
}
}
C# practice output
Cart: 3 items, €33.90 or $37.29 2 x Notebook 1 x Desk lamp Renders: badge 3, page 3, subscribers 2 After page.Dispose(): badge 4, page 3, subscribers 1 Forgotten listener rendered 1 time(s) after Dispose; subscribers 2
If a component stops updating, or keeps working after it left the screen, check that it subscribes once in OnInitialized and unsubscribes in Dispose with -= on the same named method.