In the previous article, we explored how to choose and apply the different Render Modes. It seemed straightforward enough: drop in @rendermode InteractiveAuto and you are good to go. But as soon as you start building real-world components with database queries, API calls, or JavaScript interop, you run into your first surprise:
“My component is executing requests twice… and it’s not a bug.”
In this article, we’ll break down why this happens, how state behaves in this new hybrid model, and—most importantly—how to solve these issues using the tools provided by .NET 10.
Quick Checklist
If you already have experience with Blazor and want the core takeaways right away, here is the gist:
- Using
Auto-> Always implementPersistentComponentStatewhen performing database or API calls. - Calling JavaScript -> Do it strictly inside
OnAfterRenderAsync. - Using
Server-> Monitor RAM usage in production: singletons are shared across all users. - Failing parameters -> Verify that you are passing only serializable objects across render modes.
- Need to know your execution context -> Use
RendererInfodefensively before touching browser APIs.
If any of these points raise questions, keep reading.
1. The Hidden Pitfall of Prerendering and the Component Lifecycle
Whenever you use an interactive mode (Server, WebAssembly, or Auto), Blazor enables prerendering by default. The server executes your component, renders static HTML, and streams it to the browser so the user sees the UI immediately.
Shortly after, interactivity kicks in (via SignalR or WebAssembly), and the component re-initializes in its new environment. This re-initialization is what causes the double execution that confuses so many developers at first.
The full flow with InteractiveAuto looks like this:
flowchart TD
A(["🌐 Petición inicial del usuario"])
subgraph SSR["Fase 1 — Static SSR (Prerender)"]
B["Servidor ejecuta el componente\nGenera HTML estático"]
C(["OnInitializedAsync se ejecuta\n1ª vez en servidor"])
D["HTML + estado serializado\nenviado al navegador"]
end
subgraph SERVER["Fase 2 — Interactive Server (1ª visita)"]
E["WebSocket SignalR se activa\nComponente se reinicializa"]
F(["OnInitializedAsync se ejecuta\n2ª vez via SignalR"])
G["Estado recuperado desde HTML\nsin nueva llamada a la API"]
end
subgraph WASM["Fase 3 — Interactive WASM (visitas futuras)"]
H[".NET WASM descargado\nen background"]
I(["OnInitializedAsync corre\nen el browser del cliente"])
J["Sin servidor necesario\nPura ejecución en cliente"]
end
A --> B
B --> C
C --> D
D --> E
E --> F
F --> G
G -.->|"Bundle WASM\ndescargado en bg"| H
H --> I
I --> J
OnInitializedAsync Runs Twice
If you call await _api.GetData() inside OnInitializedAsync, that call will run once on the server during prerendering and again once interactivity starts. The result: duplicate requests, potential UI flickering, and a degraded user experience.
Microsoft’s official and idiomatic solution for this is PersistentComponentState.
2. State Management: PersistentComponentState in Action
The concept is simple yet powerful: during prerendering, we persist the state directly into the HTML payload. When the interactive component wakes up, it retrieves the persisted data instead of querying the data source a second time.
Here is how we implement this on the /analytics page of our Task Manager App:
@page "/analytics"
@using TaskManagerApp.Client.Models
@using TaskManagerApp.Client.Services
@inject ITaskService TaskService
@inject PersistentComponentState ApplicationState
@implements IDisposable
@rendermode InteractiveAuto
@* ... HTML de la página ... *@
@code {
private List<TaskItem>? tasks;
private PersistingComponentStateSubscription persistingSubscription;
protected override async Task OnInitializedAsync()
{
persistingSubscription = ApplicationState.RegisterOnPersisting(PersistData);
if (!ApplicationState.TryTakeFromJson<List<TaskItem>>("tasks", out var restored))
{
// Primera vez (prerender) → vamos a buscar los datos
tasks = await TaskService.GetTasksAsync();
}
else
{
// Al activar interactividad → recuperamos el estado ya serializado
tasks = restored;
}
}
private Task PersistData()
{
if (tasks != null)
{
ApplicationState.PersistAsJson("tasks", tasks);
}
return Task.CompletedTask;
}
public void Dispose()
{
persistingSubscription.Dispose();
}
}
Important trade-off: Do not overuse this pattern. Storing excessively heavy objects bloats the initial HTML document. Reserve it for critical initial-load data, and handle large datasets through on-demand loading or pagination.
3. RendererInfo: Where on Earth Am I Running?
With InteractiveAuto, your code can execute across three distinct contexts: static server (prerender), interactive server (SignalR), and client (WebAssembly). Sometimes, you need to know exactly which runtime you are in.
Starting with .NET 9, RendererInfo gives us that capability.
Debugging Usage
<div class="alert alert-info">
<strong>Entorno actual:</strong> @RendererInfo.Name <br />
<strong>Interactivo:</strong> @(RendererInfo.IsInteractive ? "Sí" : "No (Prerendering)")
</div>
Defensive Usage (The Truly Useful One)
This prevents classic runtime errors like attempting to access localStorage during prerendering:
Bad (fails during prerender):
@code {
protected override async Task OnInitializedAsync()
{
// System.InvalidOperationException: JavaScript interop calls cannot be issued at this time.
var theme = await JS.InvokeAsync<string>("localStorage.getItem", "theme");
}
}
Safe approach using RendererInfo:
@code {
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender && RendererInfo.IsInteractive)
{
// Solo llegamos aquí cuando hay un browser real ejecutando el código
var theme = await JS.InvokeAsync<string>("localStorage.getItem", "theme");
ApplyTheme(theme);
}
}
}
Golden rule: RendererInfo.IsInteractive is your safety guard before executing any operation that requires a real browser DOM or browser APIs.
4. Major Pitfalls (Where You’ll Trip Up Most)
Hierarchies with Different Render Modes
A child component configured with InteractiveWebAssembly cannot accept complex parameters (such as an active database context instance or a service with non-serializable dependencies) from a parent running in Static SSR mode. Any parameters passed across the boundary between SSR and interactive modes must be JSON-serializable.
Calling JavaScript Outside of OnAfterRenderAsync
This is one of the most frequent and frustrating mistakes:
Failing code:
protected override async Task OnInitializedAsync()
{
await JS.InvokeVoidAsync("miFuncion"); // Explota en prerender
}
Correct code:
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await JS.InvokeVoidAsync("miFuncion"); // Seguro: el DOM ya existe
}
}
Golden rule: Any JavaScript invocation (IJSRuntime) must take place inside OnAfterRenderAsync(bool firstRender).
State in InteractiveServer
While InteractiveServer delivers snappy initial execution, all component state lives in server RAM for as long as the WebSocket connection remains open.
In the /tasks view of our project, we keep this reminder note:
protected override async Task OnInitializedAsync()
{
// En InteractiveServer, el estado se mantiene en memoria en el servidor para esta conexión SignalR.
// Ojo: Si el usuario recarga la página, esta instancia del componente se destruye y el estado interno se pierde.
tasks = await TaskService.GetTasksAsync();
}
If the server restarts or the connection drops, users will lose their transient state. Always design your architecture with the assumption that the SignalR connection can drop at any moment.
5. Real-World Performance
When you handle state and lifecycle properly, you achieve tangible performance improvements:
- WASM Payload: With
Auto, the initial download size of the .NET runtime does not penalize users because the first view renders instantly from the server via prerendering. The WASM bundle downloads silently in the background. - SignalR Scaling: By pairing Static SSR pages with only select Interactive Server pages, you drastically cut down server memory consumption. Not every visitor needs a permanent open WebSocket.
- Caching: In Static SSR, traditional Output Caching becomes immensely valuable once again using
[OutputCache]. This cannot be applied to InteractiveServer components because they are stateful.
6. Final Practical Rules
To keep these concepts top of mind without needing to memorize everything, refer back to this checklist (also summarized at the top of this article):
- Using
Auto-> Always implementPersistentComponentStatewhenever calling databases or slow APIs. - Calling JS -> Execute calls strictly inside
OnAfterRenderAsyncand guard them withfirstRenderorRendererInfo.IsInteractive. - Using
Server-> Keep an eye on production RAM usage and remember that singletons are shared across every user. - Parameter errors -> Check if you are passing non-serializable objects across different render mode boundaries.
- Calling browser APIs -> Use
RendererInfo.IsInteractiveas a defensive checkpoint before invoking them.
With these fundamentals in place, your Blazor application will be significantly faster, more reliable, and easier to predict.
What’s Next?
In the next article of this series, we’ll take things a step further and tackle “Real-World Architecture with Blazor Web Apps”: organizing large projects, designing services that run seamlessly across all render modes, and implementing robust authentication patterns.
All examples from this article are taken directly from the Task Manager App, the reference project built alongside this series. If you want to review the complete code, see how the pieces fit together, or use it as a starting point for your own apps, the repository is available on GitHub: TaskManagerApp