State Management in Blazor
Manage shared state with service singletons, Fluxor, or cascading AppState to keep UI consistent across components.
State Management Challenges in Blazor
As Blazor apps grow, managing state that must be shared across many unrelated components becomes complex. Simple prop-drilling breaks down; you need a centralized, reactive state store.
Simple State with a Scoped Service
The simplest Blazor state management: a scoped service that holds state and exposes an event so components can subscribe to changes.
public class CartState
{
private readonly List<CartItem> _items = new();
public IReadOnlyList<CartItem> Items => _items;
public int Count => _items.Sum(i => i.Quantity);
public event Action? OnChanged;
public void Add(Product p)
{
var existing = _items.FirstOrDefault(i => i.ProductId == p.Id);
if (existing is not null) existing.Quantity++;
else _items.Add(new CartItem { ProductId = p.Id, Name = p.Name, Price = p.Price });
OnChanged?.Invoke();
}
}All lessons in this course
- Blazor Component Model
- Data Binding & Event Handling
- Component Communication & DI
- State Management in Blazor