📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How do you manage state in a Blazor Web App? Explain component state, cascading values, scoped services and what 'scoped' means per circuit versus per request, browser storage, and how .NET 10 persists state across prerendering, enhanced navigation and lost circuits. What must never go in a singleton?

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.

Mid-Level Theory Intermediate blazor dependency-injection frontend persistent-state prerendering state-management

🎯 Key points

  • Component fields live only as long as the component instance; a refresh loses them
  • Static SSR: a new DI scope per HTTP request; Interactive Server: one scope for the whole circuit (one tab); WASM: scoped is effectively per app instance
  • A singleton is shared by every user in Server mode: user data there is a privacy breach, and even user-keyed caches need an ownership check on every read
  • Cascading values for context (theme, tenant settings, auth); root-level AddCascadingValue with CascadingValueSource for notifications
  • State container service with an OnChange event; components subscribe and unsubscribe in Dispose
  • [PersistentState] in .NET 10 serialises prerendered data into the page and restores it in the interactive render; keep it small and non-sensitive because it is visible in the HTML
  • .NET 10 can persist circuit state so a user resumes after the circuit is evicted; durable state still belongs in the URL, browser storage or the database
  • In interactive components get the user from AuthenticationStateProvider / Task<AuthenticationState>, not HttpContext

⏱ 30-second answer

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.

🗣 Full answer (senior)

How I would answer this in an interview

"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 OnChange event that components subscribe to and unsubscribe from in Dispose.

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 DbContext lives for hours and its change tracker grows; I use IDbContextFactory and 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 ProtectedSessionStorage in Server mode or sessionStorage through 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."


Where state can live

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

.NET 10 persistence features

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

Production example

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.

🔍 What the interviewer is checking

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

  • Explains scoped = circuit in Interactive Server and the singleton data-leak risk
  • Uses IDbContextFactory instead of a circuit-long DbContext
  • Puts shareable state in the URL and durable state in the database
  • Knows [PersistentState] and what .NET 10 adds for circuits

Red flags

  • Thinks scoped means per request in every Blazor mode
  • Stores user data in singletons or static fields
  • Treats in-memory state as durable

📚 Learn in depth

1. DI scopes in each hosting model

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.

2. Why singletons leak data

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.

3. State container pattern

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).

4. Cascading values at scale

<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.

5. Persisting across prerendering

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.

6. Circuit state persistence (.NET 10)

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.

7. Authentication state, not HttpContext

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.

Try it yourself

  1. Register a counter service as scoped, open two tabs in Server mode and see independent counts; switch to singleton and see them share.
  2. Inject a scoped DbContext into an interactive page, load 10,000 entities, and watch memory with dotnet-counters until the tab closes.
  3. Load data in a prerendered component, see two loads in the logs, then add [PersistentState] and view the page source to see the persisted state.
  4. Stop the server for 30 seconds while a form is half filled and observe what is lost; then save drafts to ProtectedSessionStorage.
  5. Put a filter in the query string and confirm refresh and Back keep it.

💻 Code

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();
    }
}

⚠ Common mistakes

  • Mistake: Storing per-user data in a singleton in Server mode. Why it is wrong: every user on the server shares it, so one user can see another's data. Instead: scoped services, or a cache keyed and checked by user id.
  • Mistake: Assuming scoped means per request in Interactive Server. Why it is wrong: the scope is the circuit, which can last hours. Instead: design scoped services for long life; use IDbContextFactory for EF Core.
  • Mistake: Injecting a scoped 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.
  • Mistake: Keeping important progress only in memory. Why it is wrong: a refresh, deployment or circuit eviction loses it. Instead: save drafts to the database or browser storage.
  • Mistake: Subscribing to a state service event without unsubscribing. Why it is wrong: the service holds the component and, in Server mode, the circuit stays in memory. Instead: unsubscribe in Dispose.
  • Mistake: Reading 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.
  • Mistake: Persisting large objects with [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.
  • Mistake: Putting sensitive data in 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.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions scoped services and singletons in Server mode Why: Checks whether they can diagnose captive dependencies and cross-user data leaks
    How to answer

    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.

  2. When: Candidate says prerendering loses state between two scopes Why: Checks whether they connect state persistence to the render mode and prerender choice
    How to answer

    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.

  3. When: Candidate mentions ProtectedSessionStorage or persisted circuit state with several instances Why: Checks whether they know Data Protection keys must be shared across replicas
    How to answer

    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.

🛠 Real-world problems: how you handle them

A user sees another customer's details after a refactor
Situation
A customer self-service portal built with Blazor Interactive Server, [~3,000 daily users], hosted on two App Service instances in Australia East. A refactor moved 'current customer' lookups into a cached service to cut database calls.
Signals
A support ticket with a screenshot showing another customer's name and address on the profile page; no errors in logs; database calls had dropped [60%] since the release, which had looked like a success.
Investigation
Reviewed the release diff and found `CurrentCustomerCache` registered with `AddSingleton` and holding a `Customer` property set on page load. Reproduced it with two browsers logged in as different users in a test environment: the second login overwrote the value the first user saw on their next render. Application Insights showed the affected page views and time window.
Resolution
Immediate: rolled back the release within [30 minutes] and invalidated sessions. Fix: changed the service to scoped (per circuit), keyed the cache by the authenticated customer id with an ownership check, and added an authorisation check in the query. The privacy officer assessed the incident under the Notifiable Data Breaches scheme.
Prevention
A two-user integration test with bUnit/Playwright asserting each user sees only their data; an architecture test that fails if services in the `State` namespace are registered as singletons; a review checklist item for every singleton in Server-mode apps; an ADR documenting Blazor DI lifetimes.

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.

More in Blazor

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me