In a Blazor component, in what order do SetParametersAsync, OnInitialized(Async), OnParametersSet(Async) and OnAfterRender(Async) run, and which run again later?
answer
- parameters are assigned first
- the sync method runs before the async one
- initialization runs once per instance
- a render after the sync part of an await
- OnAfterRender only for interactive renders
basics
~10 sOn 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 sBlazor 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@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
Recite the order - parameters, OnInitialized, OnParametersSet, render, OnAfterRender - and know that initialization runs once while parameter methods run on every update.
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.
Diagnose double loads, null-reference renders and missed reloads by mapping symptoms to lifecycle steps, including prerendering's second instance and canceled tasks.
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.