
Managing shared state across components in a Blazor WASM SPA requires a deliberate strategy. The simplest and most idiomatic approach is an AppState service registered as a singleton.
public class AppState
{
public string? UserName { get; private set; }
public int CartItemCount { get; private set; }
public event Action? OnChange;
public void SetUser(string name)
{
UserName = name;
NotifyStateChanged();
}
public void AddToCart()
{
CartItemCount++;
NotifyStateChanged();
}
private void NotifyStateChanged() => OnChange?.Invoke();
}// Program.cs
builder.Services.AddSingleton<AppState>();
// Component:
@inject AppState State
@implements IDisposable
protected override void OnInitialized() => State.OnChange += StateHasChanged;
public void Dispose() => State.OnChange -= StateHasChanged;Always unsubscribe in Dispose to prevent memory leaks.
Reference:
TaskLoco™ — The Sticky Note GOAT