Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 41 ยท State and Dependency Injection

State Containers and App State in Blazor

Share state between Blazor components with a scoped state container and change events, and keep it across reloads with browser storage and PersistentComponentState.

Parameters work between a parent and a child, and cascading values cover ambient data, but many apps also have state that unrelated components must share: the shopping cart badge in the header and the cart page, the signed-in user's preferences, a wizard's collected answers. The standard solution is a state container: a plain C# class, registered as a service, that holds the data and raises an event when it changes.

In this lesson you build one, learn the subscribe-and-dispose discipline that keeps it from leaking, and then deal with the hard part of state: persistence. A browser refresh or a lost connection destroys component and circuit state, so important data must be saved somewhere. The Razor examples are real syntax and read-only; the runnable examples are stand-ins in plain C#.

The state container pattern

A state container is just a class with data and a notification event:

C#
public class CartState
{
    private readonly List<CartLine> lines = [];

    public IReadOnlyList<CartLine> Lines => lines;
    public int Count => lines.Sum(l => l.Quantity);

    public event Action? Changed;

    public void Add(string sku, string name, decimal price)
    {
        var existing = lines.Find(l => l.Sku == sku);
        if (existing is null) lines.Add(new CartLine(sku, name, price, 1));
        else lines[lines.IndexOf(existing)] = existing with { Quantity = existing.Quantity + 1 };
        Changed?.Invoke();
    }
}

public record CartLine(string Sku, string Name, decimal Price, int Quantity);

Register it scoped, so each circuit (each user) gets its own:

C#
builder.Services.AddScoped<CartState>();

Components inject it, read from it and subscribe to Changed:

RAZOR
@implements IDisposable
@inject CartState Cart

<span class="badge">@Cart.Count</span>

@code {
    protected override void OnInitialized() => Cart.Changed += OnCartChanged;

    private void OnCartChanged() => InvokeAsync(StateHasChanged);

    public void Dispose() => Cart.Changed -= OnCartChanged;
}

The three habits are: subscribe in OnInitialized, call InvokeAsync(StateHasChanged) in the handler (the event may be raised from another thread or another component's event), and unsubscribe in Dispose. Skip the last and the long-lived container keeps every dead component alive.

flowchart LR
    P["ProductPage<br/>Add to cart"] -->|"Cart.Add()"| S["CartState<br/>(scoped service)"]
    S -->|"Changed event"| H["Header badge"]
    S -->|"Changed event"| C["Cart page"]

One writer, many readers: components never talk to each other directly.

A state container you can run

The stand-in uses the same class shape. Two "components" subscribe and print what they would render.

C# State container with change events

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

After Dispose, the page no longer renders, but the header still does. A component that forgot to unsubscribe would keep printing (and keep memory) forever.

Do not expose raw mutable data

Handing out List<CartLine> lets any component change data without raising Changed, so other components go stale. Expose IReadOnlyList<T> and only mutate through methods that notify. For richer apps, one Changed event per state class (not one giant global state) keeps updates cheap and understandable.

Where state is lost

Event Scoped service state (Server) Component fields
Navigating between pages (client router) kept lost (component removed)
Browser refresh / new tab lost lost
Connection lost, circuit expires lost lost
WebAssembly full page load lost lost

Because a refresh creates a new circuit (or a new WebAssembly runtime), service state does not survive. For anything the user would be upset to lose, persist it.

Persisting in the browser

Blazor has no built-in browser storage access, so you use JavaScript interop. localStorage survives browser restarts; sessionStorage lives per tab. The usual helper is a small service:

C#
public class LocalStore(IJSRuntime js)
{
    public ValueTask SetAsync<T>(string key, T value)
        => js.InvokeVoidAsync("localStorage.setItem", key, JsonSerializer.Serialize(value));

    public async ValueTask<T?> GetAsync<T>(string key)
    {
        var json = await js.InvokeAsync<string?>("localStorage.getItem", key);
        return json is null ? default : JsonSerializer.Deserialize<T>(json);
    }
}

Two rules apply. JS interop is only available after the first render on the server (during prerendering there is no browser), so load from storage in OnAfterRenderAsync(firstRender). And never store secrets or authoritative data this way: the user can edit it. ProtectedLocalStorage and ProtectedSessionStorage (built into Blazor Server) encrypt values, but data the server must trust should live in a database anyway.

The save-and-restore logic in a stand-in, with a dictionary as the "browser" and System.Text.Json for the serialization:

C# Persisting a state container

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Always wrap deserialization in try/catch: storage can hold old formats or garbage.

Persisting prerendered state

With prerendering, a component runs twice: once on the server to produce HTML, then again when the interactive circuit starts. Any data it loads would be fetched twice and might flicker. PersistentComponentState and the [PersistentState] attribute (since .NET 10) embed the first load's data in the page and hand it to the second run:

RAZOR
@code {
    [PersistentState]
    public List<Product>? Products { get; set; }

    protected override async Task OnInitializedAsync()
    {
        Products ??= await Service.GetAllAsync();   // only loads if nothing was persisted
    }
}

The ??= is the important part: on the second run the property is already filled, so the service is not called. Prerendering and Streaming Rendering explains when this matters.

Other places to keep state

  • URL: shareable and bookmarkable (see Query Strings and URL State).
  • Server database: the only place for data that must survive across devices and be trusted.
  • Cookies: for server-readable small values; in Blazor Server prefer scoped services for in-session data, because cookies can only be set during an HTTP request, not over the circuit.
  • Fluxor, Redux-style libraries: add structure for large apps (actions and reducers). The container pattern is the foundation of all of them.

Start with the simplest tool that holds the data long enough: component field, then parameter, then cascading value, then state container, then persistence. Each step adds complexity.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is a state container usually registered as scoped in Blazor Server?

    A singleton would be shared by every user, mixing their data; a scoped instance belongs to one circuit.
  2. 2. What must a component do when it subscribes to the container's Changed event?

    The container outlives components, so handlers must be removed, and the handler should re-render on the right context.
  3. 3. Where should code that reads localStorage through JS interop run?

    JavaScript is not available until the component is rendered in a browser.
  4. 4. A browser refresh in Blazor Server does what to scoped service state?

    Scope equals circuit; a refresh starts a fresh circuit.

Summary

  • A state container is a scoped service with data, mutation methods and a Changed event.
  • Subscribe in OnInitialized, re-render with InvokeAsync(StateHasChanged), unsubscribe in Dispose.
  • Expose read-only views and mutate only through notifying methods.
  • Refreshes and lost connections destroy in-memory state; persist important data in storage or a database.
  • PersistentComponentState carries prerendered data into the interactive run so it is loaded once.

Next: Calling APIs from Blazor with HttpClient