skip to content

Lifecycle & Rendering

ComponentBase runs SetParametersAsync, OnInitialized, OnParametersSet and OnAfterRender, and renders on StateHasChanged. Interviewers probe double initialisation when prerendered and off-thread calls.

on this pageshow

explore

questions

5

In a Blazor component, in what order do SetParametersAsync, OnInitialized(Async), OnParametersSet(Async) and OnAfterRender(Async) run, and which run again later?

level: juniorimportance: must knowfreq 72%

answer

  1. parameters are assigned first
  2. the sync method runs before the async one
  3. initialization runs once per instance
  4. a render after the sync part of an await
  5. OnAfterRender only for interactive renders

basics

~10 s

On first use: SetParametersAsync assigns parameters, then OnInitialized, OnInitializedAsync, OnParametersSet and OnParametersSetAsync run, the component renders, and OnAfterRender(Async) runs with firstRender true. Later parameter updates repeat only SetParametersAsync, OnParametersSet(Async), render and OnAfterRender.

solid answer

~40 s

Blazor creates the component, injects `[Inject]` services, then calls `SetParametersAsync`, whose `ComponentBase` implementation assigns the parameters and, the first time only, calls `OnInitialized` then `OnInitializedAsync`. If that task is still running, the component **renders once** (showing, say, a loading message) and awaits it. Next come `OnParametersSet` and `OnParametersSetAsync`, followed by a render, and another render when that task completes. After each **interactive** render, once the UI is updated, `OnAfterRender(firstRender)` and `OnAfterRenderAsync(firstRender)` run, with `firstRender` `true` only the first time. When the parent later passes new parameters, `SetParametersAsync` runs again but initialization does not: only `OnParametersSet(Async)`, a render and `OnAfterRender`. Events and `StateHasChanged` cause a render without the parameter methods. A canceled task from these methods is ignored rather than rendered as an error.

code

razor · 25 lines
razor
@inject IForecastClient Forecasts

@if (forecast is null)
{
    <p>Loading forecast...</p>
}
else
{
    <p>@forecast.Summary, @forecast.RainMm mm rain</p>
}

@code {
    [Parameter, EditorRequired] public int FieldId { get; set; }

    private int loadedFieldId;
    private Forecast? forecast;

    protected override async Task OnParametersSetAsync()
    {
        if (FieldId == loadedFieldId && forecast is not null) return;
        loadedFieldId = FieldId;
        forecast = null;
        forecast = await Forecasts.GetAsync(FieldId);
    }
}

go deeper

for a junior

Recite the order - parameters, OnInitialized, OnParametersSet, render, OnAfterRender - and know that initialization runs once while parameter methods run on every update.

for a middle

Explain the extra render after the synchronous part of an async method, why data that depends on a parameter loads in OnParametersSetAsync, and when OnAfterRender is skipped.

for a senior

Diagnose double loads, null-reference renders and missed reloads by mapping symptoms to lifecycle steps, including prerendering's second instance and canceled tasks.

for a principal

Set component conventions - where data loads, how parameter changes are detected, when SetParametersAsync may be overridden - so a large Blazor codebase behaves consistently.

## The methods involved Every Razor component normally derives from `ComponentBase` (namespace `Microsoft.AspNetCore.Components`), which turns Blazor's minimal component contract (`IComponent.SetParametersAsync`) into a set of overridable **lifecycle methods**: - `SetParametersAsync(ParameterView)` - receives the parameter values from the parent or the route; - `OnInitialized()` / `OnInitializedAsync()` - one-time setup; - `OnParametersSet()` / `OnParametersSetAsync()` - react to the current parameter values; - `OnAfterRender(bool firstRender)` / `OnAfterRenderAsync(bool firstRender)` - work that needs the rendered UI; - `StateHasChanged()` and `ShouldRender()` - request and gate re-renders. In each pair, the synchronous method runs before the asynchronous one. ## First time a component appears For a farm dashboard's `WeatherWidget` with a `FieldId` parameter: 1. The instance is created and `[Inject]` properties are set. 2. `SetParametersAsync` runs; the base implementation assigns `FieldId` and every other supplied `[Parameter]` or `[CascadingParameter]` property. 3. Because this is the first call, `OnInitialized` and then `OnInitializedAsync` run. 4. If `OnInitializedAsync` returned an unfinished task (it is awaiting the forecast API), `ComponentBase` calls `StateHasChanged` - the component renders with whatever state the synchronous part left, typically `forecast == null` and a loading message - and then awaits the task. 5. `OnParametersSet` and `OnParametersSetAsync` run, and the component renders again, now with the data. 6. If `OnParametersSetAsync` was still running, there is one more render when it completes. 7. After each render that reaches a live UI, `OnAfterRender(firstRender: true)` and `OnAfterRenderAsync(true)` run; later renders pass `false`. ## Later updates | Trigger | Methods that run | |---|---| | parent re-renders with possibly changed parameters | `SetParametersAsync`, `OnParametersSet`, `OnParametersSetAsync`, render, `OnAfterRender(false)` | | an event handler in the component (`@onclick`) | the handler, render (twice if the handler awaits), `OnAfterRender(false)` | | `StateHasChanged()` from code | render (if `ShouldRender` allows), `OnAfterRender(false)` | | component removed from the UI | `Dispose` or `DisposeAsync`, if implemented | `OnInitialized{Async}` runs **once per component instance**. So a widget that must reload when `FieldId` changes does that in `OnParametersSetAsync`, comparing with the previously loaded id, not in `OnInitializedAsync`. ## Details interviewers check - **Render before data.** The first render happens after the synchronous part of `OnInitializedAsync`, so markup must handle `null` data; that is why templates show `@if (forecast is null) { <p>Loading...</p> }`. - **Canceled tasks.** If a lifecycle task is canceled, `ComponentBase` swallows the cancellation instead of reporting an error (and skips the completion render of a canceled `OnParametersSetAsync`), so components need not catch `OperationCanceledException` there. - **No after-render on the server pass.** `OnAfterRender{Async}` is not called during static SSR or prerendering, because no live DOM exists; it starts with the first interactive render. - **Prerendering means two instances.** With prerendering on, the prerendered instance and the interactive instance are different objects, so steps 1-6 happen twice for an interactive component on its first load; keeping the prerendered data is a persisted-state topic. - **Parents and children.** A parent renders before its children exist; with synchronous initialization the parent finishes first, but with async initialization the order of parent and child completion is not fixed. - **Overriding `SetParametersAsync`.** Call `await base.SetParametersAsync(parameters)` (or pass `ParameterView.Empty`) unless you deliberately reimplement what it does, because the base method drives initialization and rendering.

  • When would you override SetParametersAsync, and what must the override do?
    Rarely: to read raw values with `parameters.TryGetValue<T>(name, out var value)` before they are assigned, to skip work when nothing relevant changed, or to handle parameters without properties. The override should normally end with `await base.SetParametersAsync(parameters)`; skipping the base call means you take over initialization and rendering, which `ComponentBase` otherwise drives.
  • How many times does the WeatherWidget render on its first interactive appearance if OnInitializedAsync awaits an HTTP call?
    Usually twice from the lifecycle: once after the synchronous part of `OnInitializedAsync` (the loading state) and once after `OnParametersSet`/`OnParametersSetAsync` (the data). A third render happens if `OnParametersSetAsync` itself returns an unfinished task. Prerendering adds a separate server-side pass on a different instance.

  • OnInitializedAsync runs every time the parent passes new parameter values.
  • Blazor waits for OnInitializedAsync to finish before rendering the component at all.
  • OnAfterRenderAsync runs during prerendering, right after the HTML is produced.
  • OnParametersSet runs before SetParametersAsync assigns the new values.
  • The async lifecycle method always runs before its synchronous counterpart.
open as a page

In an Interactive Server Blazor component, why does calling StateHasChanged from a System.Threading.Timer callback throw, and how does InvokeAsync fix it?

level: middleimportance: should knowfreq 46%

basics

~20 s

Rendering must happen on the renderer's Dispatcher, and a Timer callback runs on a thread-pool thread, so StateHasChanged throws an InvalidOperationException saying the thread is not associated with the Dispatcher. Wrapping the call in InvokeAsync runs it on the Dispatcher.

open as a page

In a Blazor weather widget, why does chart setup belong in OnAfterRenderAsync guarded by firstRender, and what happens if that method calls StateHasChanged unconditionally?

level: middleimportance: should knowfreq 52%

basics

~20 s

OnAfterRenderAsync runs only after an interactive render has reached the UI, so the chart's element exists; firstRender limits one-time setup to the first call. Calling StateHasChanged there without a guard triggers another render and another OnAfterRenderAsync, an endless render loop.

open as a page

In a Blazor weather widget that polls on a timer and holds a JavaScript chart, how should IAsyncDisposable be implemented, and when does Blazor call it?

level: seniorimportance: should knowfreq 38%

basics

~20 s

Add @implements IAsyncDisposable and, in DisposeAsync, cancel pending work, stop the timer, unsubscribe from service events and release JavaScript objects. Blazor calls it when the component leaves the UI or, on the server, when its circuit is torn down; with both interfaces only DisposeAsync runs.

open as a page

In Blazor, how do StateHasChanged, ShouldRender and the render tree diff decide what a component sends to the DOM, and when is overriding ShouldRender worth it?

level: seniorimportance: should knowfreq 34%

basics

~20 s

StateHasChanged queues one render unless one is already pending; ShouldRender can veto it except on the first render. A render rebuilds the component's render tree and diffs it against the previous one, so only changed elements, attributes and text are sent as DOM edits.

open as a page