Author : MD TAREQ HASSAN | Updated : 2020/08/31
Lifecycle overview
See:
- https://knowledge-base.havit.eu/2019/11/02/blazor-component-lifecycle-diagram/
- https://blazor-university.com/components/component-lifecycles/
Lifecycle callbacks
- https://docs.microsoft.com/en-us/aspnet/core/blazor/lifecycle
- https://blazor-tutorial.net/lifecycle-methods
- https://www.nativoplus.studio/blog/blazor-lifecycle-methods/
Lifecycle methods are not shared between components. Meaning, you have a separate set of lifecycle methods for each component that won’t collide with other components. This gives you greater control over each of them throughout their lifetime.
The Blazor application provides different synchronous as well as asynchronous lifecycle methods:
- OnInitialized
- OnInitializedAsync
- OnParametersSet
- OnParametersSetAsync
- OnAfterRender
- OnAfterRenderAsync
- ShouldRender
Counter.razor.cs
public class CounterBase: ComponentBase
{
protected int CurrentCount { get; set; }
public void IncrementCount()
{
CurrentCount++;
}
public void OnStateChanged()
{
// Note that the following line is necessary because otherwise
// Blazor would not recognize the state change and not refresh the UI
StateHasChanged();
}
protected override void OnInitialized()
{
//Log("OnInitialized is called");
}
protected override async Task OnInitializedAsync()
{
//Log("OnInitializedAsync is called");
await Task.Delay(1000);
}
protected override void OnParametersSet()
{
//Log("OnParameterSet is called");
}
protected override async Task OnParametersSetAsync()
{
//Log("OnParametersSetAsync is called");
await Task.Delay(1000);
}
protected override void OnAfterRender(bool firstRender)
{
//Log("OnAfterRender is called");
base.OnAfterRender(firstRender);
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
//Log("OnAfterRenderAsync is called");
return base.OnAfterRenderAsync(firstRender);
}
protected override bool ShouldRender()
{
//Log("ShouldRender is called");
return base.ShouldRender();
}
}