Component lifecycle

✅ Similar to Blazor Server

Blazor web applications are composed of individual, independent components that respond to user interactions, similarly to Blazor Server. Each component has its own unique lifecycle, which refers to the series of methods that are executed during various stages of the component's existence. Understanding the component lifecycle is crucial for effectively managing the state and behaviour of a component, as well as optimizing performance. In this tutorial, we will thoroughly examine each of the Blazor component lifecycle methods to ensure a clear understanding of their purpose and usage. Specifically, we will cover:

  • Blazor component stages.
  • Initialized and Dispose stage.
  • ParametersSet stage.
  • AfterRender stage.
You can download the example code used in this topic on GitHub.

Blazor component stages

A Blazor component can go through five stages:

  • SetParameters: This stage is triggered when the component is initially constructed (the parameters still not be set) or whenever the component's parameters updated from the URL or from the parent component. If the SetParametersAsync method is overridden, the OnParametersSet and OnParametersSetAsync methods should not be used.
  • Initialized: This is the stage where the component is fully constructed and the parameters are set.
  • ParametersSet: As the name implies, this stage is triggered whenever the component's parameters are updated from the URL or from the parent component.
  • AfterRender: triggered when the component passes the initialize stage or StateHasChanged called.
  • Dispose: This is the final step where the component is removed from the UI. Developers should clean up resources to prevent memory leaks or unexpected behaviours.

The stages will have the following order:

blazor-component-lifecycle-methods.png

To properly dispose of a component, it should implement the IDisposable/IAsyncDisposable interface, as the Dispose/DisposeAsync method is not a default feature.

You can customize each stage of the component lifecycle by overriding the corresponding method. Each stage has at least one method that can be overridden. In cases where a stage has two methods, one synchronous and one asynchronous, the synchronous method will execute first, followed by the asynchronous method. The table below shows the methods associated with each stage and their order of execution:

Stage Method Executing order
SetParameters SetParametersAsync 1
Initialized OnInitialized 2
Initialized OnInitializedAsync 3
ParametersSet OnParametersSet 4
ParametersSet OnParametersSetAsync 5
AfterRender OnAfterRender 6
AfterRender OnAfterRenderAsync 7
Dispose Dispose 8
Dispose DisposeAsync 9

The following video demonstrates the Blazor component lifecycle:

Initially, the component is not rendered and the lifecycle does not begin. Once the component is rendered, the lifecycle starts and progresses through the following stages: SetParameters, Initialized, ParametersSet, and AfterRender. Finally, when the component is removed from the user interface, the Dispose method is called, indicating that the component is being disposed.


Initialized and Dispose stage

The component lifecycle starts with the Initialize phase and ends with the Dispose phase. During the Initialize phase, you can perform tasks such as:

  • Fetching data from an API
  • Subscribing to events
  • Setting default values for properties
  • Executing JavaScript

Free resources after use

It is important to free resources after use, as not doing so can greatly impact performance and cause unwanted results. Some resources can be automatically collected by the garbage collector, but others may not. To free resources, you should:

  • Unsubscribe from events
  • Stop working tasks
  • Close open streams

To properly dispose of a component, you should use the @implements directive to implement the IDisposable interface and declare a public void Dispose() method to free resources. Here is an example code for the Initialize and Dispose phases:

@inject IJSRuntime JSRuntime
@inject NavigationManager NavigationManager
@implements IDisposable

<h3>InitializeAndDispose</h3>
<div>Sample Text: @SampleText</div>

@code {
    public string SampleText { get; set; } = "";

    protected override void OnInitialized()
    {
        SampleText = "Blazor School";
        NavigationManager.LocationChanged += OnLocationChanged;
    }

    public void OnLocationChanged(object? sender, LocationChangedEventArgs eventArgs) => JSRuntime.InvokeVoidAsync("alert", "Hello Navigator");
    public void Dispose() => NavigationManager.LocationChanged -= OnLocationChanged;
}

When you are disposing a resource in asynchronous, you can implement the IAsyncDisposable as well. For example:

@implements IAsyncDisposable

...

@code {
    public async ValueTask DisposeAsync()
    {
    }
}

ParametersSet stage

In this phase, you can respond to changes in the parameters, which may originate from the parent component or the URL. However, if you have overridden the SetParametersAsync method, then you should skip this stage entirely.

The image below shows how the ParametersSet phase is triggered.

paramters-set-phase.png

React to parent component changes

ParametersSet phase can be used to react to the changes from the parent component. For example:

@inject IJSRuntime JSRuntime

<div class="border border-primary border-3 m-3">
    <h3>ChildComponent</h3>
    Component Parameter: @ComponentParameter
</div>

@code {
    [Parameter]
    public string ComponentParameter { get; set; } = "";

    protected override void OnParametersSet() => JSRuntime.InvokeVoidAsync("alert", "ParametersSet phase of the CHILD component triggered.");
}

In this example, ComponentParameter is a parameter passed from the parent component. If the value of this parameter changes in the parent component, the child component will activate the ParametersSet phase.

React to parameters from URL changes

ParametersSet phase can be used to react to the changes from the URL parameters. For example:

@inject IJSRuntime JSRuntime

<div>
    Url Parameter: @UrlParameter
    <a href="/parameters-set?UrlParameter=@RandomString()">Update UrlParameter</a>
</div>

@code {
    [Parameter]
    [SupplyParameterFromQuery]
    public string? UrlParameter { get; set; } = "";

    protected override void OnParametersSet() => JSRuntime.InvokeVoidAsync("alert", "ParametersSet phase of the PARENT component triggered.");

    private string RandomString()
    {
        ...
    }
}

The following video demonstrates the ParametersSet phase:


AfterRender stage

Each time Blazor renders the UI, the AfterRender phase is triggered. During this phase, there are a number of actions that can be taken, such as:

  • Utilizing a third-party library to format the UI.
  • Gathering data on user behavior for analytics purposes.

It's important to note that these are just a few examples of the types of actions that can be performed in the AfterRender phase. The specific actions taken will depend on the requirements of the application.

@inject IJSRuntime JSRuntime

<h3>AfterRender</h3>
<button @onclick="StateHasChanged">Trigger AfterRender</button>

@code {
    protected override async Task OnAfterRenderAsync(bool firstRender) => await JSRuntime.InvokeVoidAsync("alert", $"AfterRender phase triggered with firstRender is {firstRender}");
}

The following video demonstrates the AfterRender phase:

BLAZOR SCHOOL
Designed and built with care by our dedicated team, with contributions from a supportive community. We strive to provide the best learning experience for our users.
Docs licensed CC-BY-SA-4.0
Copyright © 2021-2024 Blazor School
An unhandled error has occurred. Reload 🗙