본문으로 건너뛰기
Skillpedia
웹사이트 및 UI (프런트엔드)5.8k · #14568

support-prerendering

하는 일

이 스킬은 Blazor 페이지가 서버에서 먼저 그려지고 브라우저에서 대화형으로 넘어갈 때 생기는 문제를 고칩니다. 중복 데이터 로드, 깜빡임, 로드 시 null 오류를 겪는 .NET 개발자를 위한 스킬입니다.

사용하는 경우

  • ✓Blazor 페이지가 같은 데이터를 두 번 불러오거나 처음 로드할 때 깜빡일 때.
  • ✓사전 렌더링 단계에서 null 참조 오류가 나타날 때.
  • ✓첫 서버 렌더링에서 대화형 페이지로 상태를 넘겨야 할 때.

스킬 링크

https://github.com/dotnet/skills/blob/main/plugins/dotnet-blazor/skills/support-prerendering/SKILL.md

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/dotnet/skills/blob/main/plugins/dotnet-blazor/skills/support-prerendering/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“제 Blazor 상품 페이지가 데이터를 두 번 불러오고 깜빡입니다. 한 번만 불러오도록 고쳐 주세요.”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

에이전트가 앱의 상호 작용 설정을 읽고, 사전 렌더링 단계를 보호하며, 불러온 상태를 저장해 대화형 페이지가 재사용하게 하고, 페이지가 로드될 때의 동작을 확인합니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 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:

  • OnInitializedAsync runs twice — once during prerender (static), once when the interactive runtime attaches.
  • OnAfterRenderAsync is 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>
<
자주 묻는 질문

사전 렌더링이란 무엇인가요?

상호 작용이 시작되기 전에 서버가 페이지를 정적 HTML로 먼저 그려서 빠르게 보이게 하는 방식입니다.

정적 페이지에도 적용되나요?

아니요. 앱이 상호 작용 모드를 쓰지 않으면 고칠 전환 과정이 없습니다.

사전 렌더링을 끌 수 있나요?

네. 사전 렌더링을 끄거나 페이지를 대화형 라우팅에서 제외하는 방법을 다룹니다.

상세 정보

작성자의 원본 설명

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

인기도

GitHub 스타
5.8k
순위
#14568
라이선스
MIT
업데이트
2026. 11. 2.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬