Covers Blazor state: component fields, cascading values (including root-level AddCascadingValue), scoped state services per circuit or per WASM app, URL and browser storage (ProtectedSessionStorage), [PersistentState] for prerendering and enhanced navigation, circuit state persistence in .NET 10, and the singleton data-leak risk.
Blazor state lives at several levels. Component fields last as long as the component. Cascading values share context down the tree. Scoped services share state across components, but in Interactive Server "scoped" means one circuit (one browser tab for its whole life), not one HTTP request as in static SSR; in WebAssembly it effectively means the app instance. A singleton in Server mode is shared by every user, so user data there is a data breach.
Durable or shareable state goes in the URL, browser storage (ProtectedSessionStorage in Server mode) or the database. In .NET 10, [PersistentState] serialises data loaded during prerendering into the page and restores it when the component becomes interactive, so there is no second load and no flicker; and Blazor can persist circuit state so a user can resume after a disconnect. The trade-off is the convenience of in-memory state against memory per user and loss on refresh.
"I think about Blazor state in layers. The smallest is component state: private fields that last as long as the component instance. For data many components need, I either pass it down with parameters, use a cascading value for context such as the current theme or tenant settings, or put it in a scoped state service with an
OnChangeevent that components subscribe to and unsubscribe from inDispose.The thing that catches people is what 'scoped' means. In Interactive Server, the DI scope is the circuit, which is one browser tab, for as long as that tab stays connected. So a scoped
DbContextlives for hours and its change tracker grows; I useIDbContextFactoryand create a short-lived context per operation. In WebAssembly there is one scope for the app, so scoped and singleton behave alike. And a singleton in Server mode is shared across every user on that server. For example, at [company] we found a cache of 'current user preferences' registered as a singleton, and [one user briefly saw another's settings]; under the Privacy Act that is a reportable risk, so I treat 'user data in a singleton' as a blocking review comment.State also disappears more often than people expect: a refresh, a new tab, a server restart or a circuit eviction. So I put anything shareable in the URL, small per-tab drafts in
ProtectedSessionStoragein Server mode orsessionStoragethrough interop in WebAssembly, and anything that matters in the database. .NET 10 helps in two places:[PersistentState]on a property carries data loaded during prerendering into the interactive render so it is not loaded twice, and Blazor can persist circuit state so a user who comes back after the circuit was evicted resumes where they were. The senior line: in-memory state is a cache, never the source of truth."
| Place | Lifetime | Shared with | Good for | Not for |
|---|---|---|---|---|
| Component fields | Component instance | That component | UI state (expanded, selected) | Anything needed after navigation |
| Cascading value | Provider's lifetime | Descendants | Theme, culture, auth state, form context | Fast-changing app state |
| Scoped service (Server) | Circuit (tab) | All components in that tab | Cart, wizard progress | Data needed after refresh |
| Scoped service (WASM) | App instance in the tab | All components | Client-side app state | Secrets |
| Singleton (Server) | Process | Every user | Read-only reference data, caches keyed safely | Any per-user data |
| URL (path/query) | Forever (bookmark) | Anyone with the link | Filters, ids, paging | Sensitive data |
ProtectedSessionStorage / ProtectedLocalStorage |
Tab / browser | That user | Drafts, preferences (Server mode) | Large data, secrets |
| Database | Durable | Per your rules | Source of truth | UI-only state |
| Feature | Solves |
|---|---|
[PersistentState] on a component property |
Data loaded during prerender is serialised into the page and restored in the interactive render; no double load or flicker |
[PersistentState(AllowUpdates = true)] |
Refreshes the persisted value during enhanced navigation |
| Circuit state persistence | Interactive Server: component state saved when a circuit is evicted or paused, restored when the user reconnects to a new circuit |
Root-level cascading values (AddCascadingValue) |
Cascading values that work across render-mode boundaries |
A multi-step application form in Interactive Server kept progress in a scoped service. During deployments every circuit dropped and users lost [10–15 minutes] of input, generating about [40] complaints per release. Saving each completed step to the database as a draft and keeping only the current step in memory brought complaints to near zero and let users continue on another device.
Checks that the candidate understands where Blazor state lives, how long it lasts in each hosting model, and the privacy risk of shared state.
Green flags
IDbContextFactory instead of a circuit-long DbContext[PersistentState] and what .NET 10 adds for circuitsRed flags
Static SSR: each HTTP request creates a new scope, disposed when the response ends
[GET /a] scope 1 ... disposed [GET /b] scope 2 ... disposed
Interactive Server: one scope for the whole circuit
[tab opens] --- scope created --- ... hours ... --- [tab closes / evicted] --- disposed
Interactive WebAssembly: one root scope per app instance in the tab (scoped ~ singleton)
A page that prerenders and then becomes interactive gets two scopes: one for the prerender HTTP request and one for the circuit (or the WASM app). That is why data loaded during prerender is gone in the interactive render unless you persist it.
In Server mode all circuits share one process. A singleton UserPreferencesCache with a single Current property is overwritten by whichever user touched it last. A dictionary keyed by user id looks safer, but it is only safe if every code path takes the key from the authenticated user (not from a route value or a field set earlier), and checks ownership on read. One forgotten check, or a key taken from a query string, exposes another user's data. Analysers will not catch this; code review, architecture tests and two-user tests must.
Component A --calls--> CartState.Add(item) --raises--> OnChange
Component B --subscribed--> InvokeAsync(StateHasChanged) --> re-render
Component B.Dispose() --> unsubscribe (else the service keeps B alive)
Register it scoped. Because the event may fire from another component's handler, subscribers call InvokeAsync(StateHasChanged).
<CascadingValue> makes every consumer subscribe to changes; with IsFixed="true" there is no subscription. Since .NET 8, builder.Services.AddCascadingValue(sp => ...) registers a root-level value, and CascadingValueSource<T> lets you push updates with NotifyChangedAsync. Root-level values cross render-mode boundaries, which a <CascadingValue> in a static layout cannot do.
Before .NET 10 you injected PersistentComponentState, registered a callback with RegisterOnPersisting, and read with TryTakeFromJson. In .NET 10 you put [PersistentState] on a public property. During prerender, Blazor serialises the property's value into the HTML; when the component becomes interactive, it restores it before OnInitializedAsync runs, so the usual pattern is Products ??= await LoadAsync().
Two costs: the serialised data is part of the page, so a large list makes the first response bigger and the browser parses it twice (HTML and state); and anything persisted is readable in the page source. Persist small, display-only DTOs, never secrets or fields the user should not see.
When a circuit is disconnected long enough to be evicted, or is paused on purpose, Blazor can save the circuit's declared persistent component state and restore it when the browser reconnects with a new circuit. It is in-memory by default (configurable through circuit options, or a distributed HybridCache for multiple instances), so it improves the reconnect experience but is not a durability guarantee across a deployment.
IHttpContextAccessor.HttpContext is meaningful during static SSR and prerendering, but in an interactive Server component the code runs on a SignalR message, not an HTTP request. Get the user from AuthenticationStateProvider or a [CascadingParameter] Task<AuthenticationState> (set up by AddCascadingAuthenticationState()). For WebAssembly, .NET 8+ serialises the server's authentication state to the client with AddAuthenticationStateSerialization() / AddAuthenticationStateDeserialization(); the API still authorises every call, typically with the auth cookie (BFF) rather than a token stored in the browser.
DbContext into an interactive page, load 10,000 entities, and watch memory with dotnet-counters until the tab closes.[PersistentState] and view the page source to see the persisted state.ProtectedSessionStorage.A scoped cart state container, a component that uses it, and [PersistentState] to avoid the double load.
// CartState.cs: one instance per circuit (Server) or per app (WASM)
namespace Shop.State;
public sealed class CartState
{
private readonly List<CartItem> items = [];
public IReadOnlyList<CartItem> Items => items;
public event Func<Task>? OnChange;
public async Task AddAsync(CartItem item)
{
items.Add(item);
if (OnChange is not null) await OnChange.Invoke();
}
}
public sealed record CartItem(int ProductId, string Name, decimal Price);
// Program.cs
builder.Services.AddScoped<CartState>(); // per circuit, NOT AddSingleton
builder.Services.AddDbContextFactory<ShopDb>(o => o.UseSqlServer(connectionString)); // short-lived contexts
builder.Services.AddCascadingValue(_ => new UiSettings(Currency: "AUD")); // root-level cascade
public sealed record UiSettings(string Currency);
@* CartBadge.razor *@
@implements IDisposable
@inject CartState Cart
<span>Cart (@Cart.Items.Count)</span>
@code {
protected override void OnInitialized() => Cart.OnChange += Refresh;
private Task Refresh() => InvokeAsync(StateHasChanged);
public void Dispose() => Cart.OnChange -= Refresh; // otherwise CartState keeps this component alive
}
@* Products.razor: prerendered, interactive; loads once thanks to [PersistentState] *@
@page "/products"
@rendermode InteractiveServer
@inject IDbContextFactory<ShopDb> DbFactory
@foreach (var p in Products ?? [])
{
<ProductCard Product="p" />
}
@code {
[CascadingParameter] public UiSettings Settings { get; set; } = default!;
// .NET 10: value from the prerender is restored before OnInitializedAsync
[PersistentState] public List<ProductDto>? Products { get; set; }
protected override async Task OnInitializedAsync()
{
if (Products is not null) return; // restored from prerender
await using var db = await DbFactory.CreateDbContextAsync();
Products = await db.Products.AsNoTracking()
.Select(p => new ProductDto(p.Id, p.Name, p.Price))
.Take(50).ToListAsync();
}
}
IDbContextFactory for EF Core.DbContext into interactive components. Why it is wrong: it lives for the circuit, tracks ever more entities, and is not thread-safe when two handlers overlap. Instead: create a context per operation from IDbContextFactory.Dispose.HttpContext in interactive components. Why it is wrong: there is no current HTTP request on a SignalR message, so values are null or stale. Instead: capture what you need during SSR or use AuthenticationStateProvider.[PersistentState]. Why it is wrong: the data is embedded in the HTML, slowing first load and exposing it in the page source. Instead: persist small DTOs only.localStorage from WebAssembly. Why it is wrong: any script on the page can read it. Instead: keep it on the server and fetch on demand.State design in Blazor is mostly about lifetime and blast radius. In Server mode, memory per circuit times concurrent users is your capacity limit, and anything shared across circuits is a potential privacy incident. I keep circuits thin: ids and UI state in memory, data fetched on demand, durable progress in the database. I also decide early whether the app must survive deployments mid-session, because that drives whether in-memory state is acceptable at all.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Component fields | UI-only state | Lost on navigation | Shared or durable data |
| Scoped state service | Shared within a tab (cart, wizard) | Memory per circuit; lost on refresh | Must survive deployments |
| URL state | Filters, ids, paging | Validation, length | Sensitive values |
| Browser storage | Drafts, preferences | Size limits, user-controlled | Secrets, authoritative data |
| Database drafts | Long forms, cross-device | Writes and clean-up | Trivial UI toggles |
[PersistentState] / circuit persistence |
Avoid double loads; smoother reconnects | Page size; in-memory by default | As a durability guarantee |
I measure memory per circuit with dotnet-counters and a load test, and review every singleton registration in Server-mode apps.
A captive dependency is a service held by a consumer that lives longer than it should. Most often a scoped service (such as DbContext or a current-user service) is injected into a singleton, so it is created once and shared by every request. That leads to cross-user data leaks, "A second operation was started on this context instance", stale tracked entities and ObjectDisposedException.
ValidateScopes throws when a scoped service is resolved from the root or from a singleton. ValidateOnBuild checks every registration when the provider is built. Both are on only in Development by default, so turn them on in tests too.
The fix is either to make the consumer scoped, or to inject IServiceScopeFactory and create a scope per unit of work. A transient captured by a singleton is also captive, and validation won't catch it.
A Blazor Web App decides per component where rendering happens. Static SSR (the default) renders HTML on the server for each request with no live interactivity, like Razor Pages. Interactive Server keeps component state on the server in a circuit and sends UI diffs over a SignalR WebSocket. Interactive WebAssembly downloads the .NET runtime and your assemblies and runs components in the browser, calling your API over HTTP. Interactive Auto starts on Server for a fast first load, then uses WebAssembly on later visits once the bundle is cached.
Interactive modes prerender on the server by default. The trade-off: Server is quick to start and keeps code private, but costs latency on every click and memory per connected user; WebAssembly scales cheaply but has a multi-megabyte first download.
ASP.NET Core's Data Protection system encrypts auth cookies and antiforgery tokens with a key ring. By default each instance creates its own key ring on local disk, so a cookie protected by replica A cannot be decrypted by replica B, and every redeploy creates new keys. Fix it by persisting keys to a shared store (PersistKeysToAzureBlobStorage), protecting them at rest with Key Vault (ProtectKeysWithAzureKeyVault) and setting the same SetApplicationName on every instance. If the app uses session, back it with IDistributedCache (Redis) so any replica can read it. Sticky sessions only hide the problem: they break on scale-in, deploys and pod rescheduling, so treat them as a stopgap, not the fix.
How to tell it (STAR)
**S:** At [company], our Blazor Server customer portal served [~3,000] users a day, and after a caching refactor a customer reported seeing someone else's address. **T:** As [my role] I had to contain it, find the cause and make sure it could not recur. **A:** I rolled back within [30 minutes], then found the new cache registered as a singleton, so all circuits shared one 'current customer'. I reproduced it with two browsers, changed it to a scoped, user-keyed service with an ownership check, worked with our privacy officer on the NDB assessment, and added a two-user test and an architecture test banning singletons for user state. **R:** No repeat in [12 months], the database savings stayed at [about 55%], and the lifetime rule went into our team's Blazor guidelines.
Last updated 23 Nov 2026.