skip to content

In ASP.NET Core 10 Blazor, how does [PersistentState] stop a prerendered component from loading its data twice, and what code did it replace?

level: seniorimportance: should knowfreq 45%

answer

  1. prerender, then initialize again interactively
  2. [PersistentState] on a public property
  3. Cakes ??= await LoadAsync()
  4. replaced RegisterOnPersisting + TryTakeFromJson
  5. RegisterPersistentService for scoped services

basics

~20 s

A prerendered component initializes twice: once on the server for HTML, then again when it becomes interactive. [PersistentState] on a public property serializes its prerendered value into the page and restores it before the interactive OnInitializedAsync, so Cakes ??= await Load() skips the second load.

solid answer

~40 s

With prerendering, `OnInitializedAsync` runs on the server to produce HTML, then the component starts again interactively and runs it a second time, so the cake list is fetched twice and the UI may flicker. In ASP.NET Core 10, marking a **public** property `[PersistentState]` makes the framework persist its value through the `PersistentComponentState` service when prerendering ends and restore it into the interactive instance before initialization; writing `Cakes ??= await Catalog.GetTodaysCakesAsync();` then loads only once. Before 10 you injected `PersistentComponentState`, called `TryTakeFromJson` in `OnInitializedAsync`, registered a callback with `RegisterOnPersisting` that called `PersistAsJson`, and disposed the subscription. The value travels in the page: Data Protection protects it for Interactive Server, but for WebAssembly or Auto the browser can read it, so never persist secrets. Scoped services use `RegisterPersistentService<T>`.

code

razor · 23 lines
razor
@page "/cakes"
@rendermode InteractiveServer
@inject CakeCatalog Catalog

@if (Cakes is null)
{
    <p>Loading today's cakes...</p>
}
else
{
    @foreach (var cake in Cakes)
    {
        <p>@cake.Name - @cake.Price.ToString("C")</p>
    }
}

@code {
    [PersistentState]
    public List<CakeSummary>? Cakes { get; set; }

    protected override async Task OnInitializedAsync() =>
        Cakes ??= await Catalog.GetTodaysCakesAsync();
}

go deeper

for a junior

Recall that prerendering runs initialization twice and that [PersistentState] with ??= keeps data loaded on the server.

for a middle

Explain how the value is persisted into the page and restored before initialization, and what the pre-10 imperative code looked like.

for a senior

Persist only small, safe DTOs, handle services with RegisterPersistentService, and use AllowUpdates or RestoreBehavior deliberately.

for a principal

Decide whether prerendering is worth its double initialization per page, and what data may ever be embedded in a page.

## Why prerendered components load twice Interactive render modes prerender by default. For the first request: 1. The server creates the component, runs `OnInitializedAsync`, renders HTML and discards the instance. 2. When the Blazor script starts, a **new** instance is created in the interactive runtime (circuit or WebAssembly) and `OnInitializedAsync` runs again. A page that loads today's cakes from a service therefore queries twice, and between the two the user may see the prerendered list replaced by a loading state and then the list again. **Persistent component state** hands the first pass's data to the second. ## The declarative model in ASP.NET Core 10 ASP.NET Core 10 adds the `[PersistentState]` attribute: - Put it on a **public** property of a component; the framework uses reflection on public members. - When prerendering completes, the property's value is serialized to JSON through the `PersistentComponentState` service and embedded in the response. - When the component starts interactively, the value is restored into the property **before** `OnInitializedAsync` runs. - Initialization uses `??=` so that it loads only when nothing was restored. Two options shape restoration: | Option | Default | Effect | |---|---|---| | `AllowUpdates` | `false` | When `true`, the property accepts newer persisted values during later enhanced navigations to the page | | `RestoreBehavior` | `Default` | `SkipInitialValue` skips the prerendered value; `SkipLastSnapshot` skips the value saved when a circuit paused, to force fresh data after reconnection | By default the state is loaded only when the component first initializes, so a later enhanced navigation does not overwrite, for example, a form the user is editing. ## The code it replaced Before ASP.NET Core 10, the same result needed the imperative API, which still works: 1. Inject `PersistentComponentState`. 2. In `OnInitializedAsync`, call `TryTakeFromJson<List<Cake>>("cakes", out var restored)`; if it fails, load from the service. 3. Register `RegisterOnPersisting(() => { state.PersistAsJson("cakes", Cakes); return Task.CompletedTask; })`. 4. Keep the returned `PersistingComponentStateSubscription` and dispose it in `Dispose`. The imperative form remains useful for custom keys or values that are not simple properties. ## Services State that lives in a scoped service, such as a `CakeBasket`, can be persisted too: mark the service's public properties `[PersistentState]`, register the service as scoped, and call `RegisterPersistentService<CakeBasket>(renderMode)` on the Razor components builder. The render mode argument says which interactive runtimes should receive the state. ## Security and size The persisted state is part of the page sent to the browser. - For **Interactive Server**, ASP.NET Core Data Protection protects it in transit to the circuit. - For **Interactive WebAssembly** and **Auto**, the data is delivered to code running in the browser, so the user can read it. Do not persist secrets, other users' data or anything the client must not see. - Every persisted byte is added to the response; persist the cakes shown on the page, not the whole catalogue. - Values must be JSON serializable; cyclic graphs and EF Core entities with navigation loops do not serialize cleanly, so persist simple DTOs. ## Diagnosing a double load Symptoms that point at missing persistence: - Logs or database traces show the same query twice per full page load, a few hundred milliseconds apart. - The page renders the list, flashes a loading message, and renders it again. - Values that change on every load, such as a random featured cake, visibly switch when the page becomes interactive. - Server-side metrics count twice as many catalogue calls as page views. The fix is the same each time: make the loaded value a public `[PersistentState]` property and load it with `??=`, or, if the data must be fresh on the interactive pass, mark it `RestoreBehavior = RestoreBehavior.SkipInitialValue` and accept the second load deliberately. ## Limits worth knowing - With interactive routing, internal navigation does not prerender, so there is nothing to persist; only full page loads use this path. - The same `[PersistentState]` properties also feed .NET 10's circuit state persistence on Interactive Server, which saves them when a circuit is evicted or paused.

  • A developer marks a private field [PersistentState] and the data still loads twice; why?
    The declarative model persists **public properties**; the framework finds them by reflection, and the documentation requires `public`. A private field is ignored, so nothing is restored and `??=` loads again. Make it a public property, or use the imperative `PersistentComponentState` API for anything else.
  • A WebAssembly page persists a list of customers' cake orders with [PersistentState]; what is the risk?
    For WebAssembly and Auto, the persisted JSON is delivered to the browser and can be read by the user. Only data the current user may see belongs there; other customers' orders or internal fields must not be persisted, whatever the page renders.

  • OnInitializedAsync runs only once even when prerendering is enabled.
  • [PersistentState] works on private fields as well as public properties.
  • Persisted prerender state is encrypted from the user in WebAssembly mode.
  • [PersistentState] stores the value in a database between visits.
  • PersistentComponentState was removed in ASP.NET Core 10.

Assumes ASP.NET Core 10; [PersistentState], RegisterPersistentService, AllowUpdates and RestoreBehavior are new in 10, while PersistentComponentState with TryTakeFromJson and RegisterOnPersisting dates from .NET 6.