ASP.NET Core Blazor lifecycle

By Luke Latham and Daniel Roth

The Blazor framework includes synchronous and asynchronous lifecycle methods. Override lifecycle methods to perform additional operations on components during component initialization and rendering.

Lifecycle methods

Component initialization methods

OnInitializedAsync and OnInitialized are invoked when the component is initialized after having received its initial parameters from its parent component. Use OnInitializedAsync when the component performs an asynchronous operation and should refresh when the operation is completed. These methods are only called one time when the component is first instantiated.

For a synchronous operation, override OnInitialized:

protected override void OnInitialized()
{
    ...
}

To perform an asynchronous operation, override OnInitializedAsync and use the await keyword on the operation:

protected override async Task OnInitializedAsync()
{
    await ...
}

Before parameters are set

SetParametersAsync sets parameters supplied by the component's parent in the render tree:

public override async Task SetParametersAsync(ParameterView parameters)
{
    await ...

    await base.SetParametersAsync(parameters);
}

ParameterView contains the entire set of parameter values each time SetParametersAsync is called.

The default implementation of SetParametersAsync sets the value of each property with the [Parameter] or [CascadingParameter] attribute that has a corresponding value in the ParameterView. Parameters that don't have a corresponding value in ParameterView are left unchanged.

If base.SetParametersAync isn't invoked, the custom code can interpret the incoming parameters value in any way required. For example, there's no requirement to assign the incoming parameters to the properties on the class.

After parameters are set

OnParametersSetAsync and OnParametersSet are called:

  • When the component is initialized and has received its first set of parameters from its parent component.
  • When the parent component re-renders and supplies:
    • Only known primitive immutable types of which at least one parameter has changed.
    • Any complex-typed parameters. The framework can't know whether the values of a complex-typed parameter have mutated internally, so it treats the parameter set as changed.
protected override async Task OnParametersSetAsync()
{
    await ...
}

Note

Asynchronous work when applying parameters and property values must occur during the OnParametersSetAsync lifecycle event.

protected override void OnParametersSet()
{
    ...
}

After component render

OnAfterRenderAsync and OnAfterRender are called after a component has finished rendering. Element and component references are populated at this point. Use this stage to perform additional initialization steps using the rendered content, such as activating third-party JavaScript libraries that operate on the rendered DOM elements.

The firstRender parameter for OnAfterRenderAsync and OnAfterRender:

  • Is set to true the first time that the component instance is rendered.
  • Can be used to ensure that initialization work is only performed once.
protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender)
    {
        await ...
    }
}

Note

Asynchronous work immediately after rendering must occur during the OnAfterRenderAsync lifecycle event.

Even if you return a Task from OnAfterRenderAsync, the framework doesn't schedule a further render cycle for your component once that task completes. This is to avoid an infinite render loop. It's different from the other lifecycle methods, which schedule a further render cycle once the returned task completes.

protected override void OnAfterRender(bool firstRender)
{
    if (firstRender)
    {
        ...
    }
}

OnAfterRender and OnAfterRenderAsync aren't called when prerendering on the server.

Suppress UI refreshing

Override ShouldRender to suppress UI refreshing. If the implementation returns true, the UI is refreshed:

protected override bool ShouldRender()
{
    var renderUI = true;

    return renderUI;
}

ShouldRender is called each time the component is rendered.

Even if ShouldRender is overridden, the component is always initially rendered.

State changes

StateHasChanged notifies the component that its state has changed. When applicable, calling StateHasChanged causes the component to be rerendered.

Handle incomplete async actions at render

Asynchronous actions performed in lifecycle events might not have completed before the component is rendered. Objects might be null or incompletely populated with data while the lifecycle method is executing. Provide rendering logic to confirm that objects are initialized. Render placeholder UI elements (for example, a loading message) while objects are null.

In the FetchData component of the Blazor templates, OnInitializedAsync is overridden to asychronously receive forecast data (forecasts). When forecasts is null, a loading message is displayed to the user. After the Task returned by OnInitializedAsync completes, the component is rerendered with the updated state.

Pages/FetchData.razor in the Blazor Server template:

@page "/fetchdata"
@using MyBlazorApp.Data
@inject WeatherForecastService ForecastService

<h1>Weather forecast</h1>

<p>This component demonstrates fetching data from a service.</p>

@if (_forecasts == null)
{
    <p><em>Loading...</em></p>
}
else
{
    <table class="table">
        <!-- forecast data in table element content -->
    </table>
}

@code {
    private WeatherForecast[] _forecasts;

    protected override async Task OnInitializedAsync()
    {
        _forecasts = await ForecastService.GetForecastAsync(DateTime.Now);
    }
}

Component disposal with IDisposable

If a component implements IDisposable, the Dispose method is called when the component is removed from the UI. The following component uses @implements IDisposable and the Dispose method:

@using System
@implements IDisposable

...

@code {
    public void Dispose()
    {
        ...
    }
}

Note

Calling StateHasChanged in Dispose isn't supported. StateHasChanged might be invoked as part of tearing down the renderer, so requesting UI updates at that point isn't supported.

Handle errors

For information on handling errors during lifecycle method execution, see Handle errors in ASP.NET Core Blazor apps.