support-prerendering
O que ela faz
Esta skill corrige problemas que acontecem quando páginas Blazor são desenhadas primeiro no servidor e depois assumidas pelo navegador. É para desenvolvedores .NET que veem cargas de dados duplicadas, cintilação ou erros de null ao carregar.
Quando usar
- ✓Quando uma página Blazor carrega os mesmos dados duas vezes ou pisca no primeiro carregamento.
- ✓Quando um erro de referência nula aparece durante a etapa de pré-renderização.
- ✓Quando você precisa que o estado passe da primeira renderização no servidor para a página interativa.
Link da skill
https://github.com/dotnet/skills/blob/main/plugins/dotnet-blazor/skills/support-prerendering/SKILL.mdCopie e cole na sua IA (Claude, ChatGPT ou Cursor) pedindo para seguir as instruções.
Como usar
O jeito mais fácil: copie a mensagem e cole na sua IA. Ela lê a skill e segue as instruções.
Mensagem pronta para colar
Para Claude Code, Codex ou Cursor: rode na pasta do projeto e a skill fica instalada.
Baixe o SKILL.md e coloque na pasta de skills do seu agente.
Exemplo do que pedir para a IA
“Minha página de produto em Blazor carrega os dados duas vezes e pisca. Corrija para que carregue uma vez só.”
5 skills novas por semana. 1 minuto de leitura.
Como funciona
O agente lê as configurações de interatividade do app, protege a etapa de pré-renderização, persiste o estado carregado para que a página interativa o reutilize e verifica como a página se comporta ao carregar.
Conteúdo técnico (SKILL.md original)
Texto original do autor, em inglês, direto do GitHub.
Support Prerendering
How Prerendering Works
Prerendering is on by default for all interactive render modes. The server renders the component as static HTML and ships it to the browser immediately. Then the interactive runtime (Server/WebAssembly) loads and re-renders the component with full interactivity.
This means:
OnInitializedAsyncruns twice — once during prerender (static), once when the interactive runtime attaches.OnAfterRenderAsyncis NOT called during prerender — only after the interactive render.- Internal navigation between interactive pages (interactive routing) skips prerendering — prerendering only happens on full page loads.
Step 1 — Read the Project's AGENTS.md
Check the project's AGENTS.md for the Interactivity Mode and Interactivity Scope:
| Mode | Prerendering applies? |
|---|---|
| None (Static SSR) | No — there's no interactive handoff |
| Server | Yes |
| WebAssembly | Yes |
| Auto | Yes |
If the mode is None, this skill doesn't apply.
Persist State Across Prerender → Interactive
The most common prerendering problem: data loaded in OnInitializedAsync during prerender is thrown away and re-fetched when the interactive runtime attaches. This causes flicker and duplicate API/DB calls.
Recommended: [PersistentState] attribute
Annotate properties to automatically serialize during prerender and restore on interactive activation:
@page "/forecasts"
@rendermode InteractiveServer
<h1>Weather</h1>
@if (Forecasts is null)
{
<p>Loading...</p>
}
else
{
@foreach (var f in Forecasts)
{
<p>@f.Date: @f.TemperatureC°C</p>
}
}
@code {
[PersistentState]
public WeatherForecast[]? Forecasts { get; set; }
protected override async Task OnInitializedAsync()
{
Forecasts ??= await ForecastService.GetForecastsAsync();
}
}
The ??= pattern is critical — it means "only fetch if the property wasn't already restored from prerender state."
Multiple instances of the same component
When the same component type appears multiple times, use @key to disambiguate state:
@foreach (var item in items)
{
<ItemCard @key="item.Id" />
}
Advanced: PersistentComponentState service
For complex scenarios (dynamic keys, custom serialization), use the imperative API:
@inject PersistentComponentState ApplicationState
@code {
private List<Order>? orders;
protected override async Task OnInitializedAsync()
{
ApplicationState.RegisterOnPersisting(PersistOrders);
if (!ApplicationState.TryTakeFromJson<List<Order>>("orders", out var restored))
{
orders = await OrderService.GetOrdersAsync();
}
else
{
orders = restored;
}
}
private Task PersistOrders()
{
ApplicationState.PersistAsJson("orders", orders);
return Task.CompletedTask;
}
}
Disable Prerendering
Disable prerendering when a component depends on browser APIs immediately or when the prerender+interactive double render causes problems you can't solve with [PersistentState].
On a component definition
@rendermode @(new InteractiveServerRenderMode(prerender: false))
Replace InteractiveServerRenderMode with InteractiveWebAssemblyRenderMode or InteractiveAutoRenderMode as needed.
On a component instance
<MyChart @rendermode="new InteractiveServerRenderMode(prerender: false)" />
On the entire app
In App.razor:
<HeadOutlet @rendermode="new InteractiveServerRenderMode(prerender: false)" />
<Routes @rendermode="new InteractiveServerRenderMode(prerender: false)" />
Note: A parent's prerendering setting overrides children. If <Routes> disables prerendering, individual pages cannot re-enable it.
Exclude Pages from Interactive Routing
In a globally interactive app, some pages may need HttpContext (cookies, request headers, response status codes). These pages must render via static SSR, not inside the interactive runtime.
Use [ExcludeFromInteractiveRouting]:
@page "/privacy"
@attribute [ExcludeFromInteractiveRouting]
<h1>Privacy Policy</h1>
This forces a full page reload when navigating to this page, exiting interactive routing. The page renders as static SSR with full HttpContext access.
In App.razor, conditionally apply the render mode:
<!DOCTYPE html>
<html>
<
Perguntas frequentes
O que é pré-renderização?
É o servidor desenhar a página primeiro como HTML estático, para que ela apareça rápido antes de a interatividade começar.
Ela se aplica a páginas estáticas?
Não. Se o app não usa modo interativo, não há passagem a corrigir.
Dá para desligar a pré-renderização?
Sim. A skill cobre desativar a pré-renderização ou excluir páginas do roteamento interativo.
Detalhes
Descrição original do autor
Make interactive Blazor components work correctly with prerendering. USE FOR fixing duplicate data loads, UI flicker during prerender-to-interactive handoff, null references during prerender, persisting state across prerender, disabling prerendering, excluding pages from interactive routing, or detecting whether a component is currently prerendering. DO NOT USE for choosing which render mode to use (see create-blazor-project) or general component authoring (see author-component).
repo: dotnet/skills
Popularidade
- Estrelas no GitHub
- 5,8 mil
- Posição no ranking
- #14568
- Licença
- MIT
- Atualizada em
- 02/11/2026
Comentários
- …
Mais skills deste repositório
create-custom-agent
5,8 milAjuda seu agente a criar arquivos de agentes personalizados para o VS Code, com suas próprias ferramentas, instruções e transferências para outros agentes.
create-skill
5,8 milAjuda seu agente a criar uma nova skill de agente com nome válido, uma descrição clara de quando usá-la e um arquivo SKILL.md que segue o padrão.
csharp-scripts
5,8 milAjuda seu agente a rodar um pequeno programa C# como um único arquivo com a ferramenta de linha de comando do .NET, sem criar um projeto completo.
dotnet-pinvoke
5,8 milAjuda seu agente a chamar corretamente bibliotecas nativas em C ou C++ a partir do .NET, cobrindo assinaturas, tratamento de strings, memória e handles seguros.
Skills parecidas
angular-developer
280 milAjuda seu agente a criar código Angular e a dar conselhos sobre a estrutura do projeto. É útil para iniciar novos projetos, criar partes do código ou melhorar a performance e acessibilidade.
frontend-a11y
280 milAjuda seu agente a tornar interfaces web acessíveis para todos. Ele garante que sites e apps funcionem bem com leitores de tela e navegação por teclado.
frontend-patterns
280 milFaz seu agente aplicar padrões modernos no desenvolvimento frontend. Ele otimiza performance, gerencia estado e segue boas práticas em React e Next.js.