Lifecycle overview

Blazor Component Lifecycle

See:

Lifecycle callbacks

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:

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 Task OnAfterRenderAsync(bool firstRender)
	{
		//Log("OnAfterRenderAsync is called");
		return base.OnAfterRenderAsync(firstRender);
	}

	protected override bool ShouldRender()
	{
		//Log("ShouldRender is called");
		return base.ShouldRender();
	}
}