✅ Similar to Blazor WebAssembly
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:
You can download the example code used in this topic on GitHub.
A Blazor component can go through five stages:
SetParametersAsync
method is overridden, the OnParametersSet
and OnParametersSetAsync
methods should not be used.StateHasChanged
called.The stages will have the following order:
To properly dispose of a component, it should implement theIDisposable/IAsyncDisposable
interface, as theDispose/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.
The component lifecycle starts with the Initialize phase and ends with the Dispose phase. During the Initialize phase, you can perform tasks such as:
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:
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() { } }
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.
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.
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:
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:
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: