Component Lifecycle

A component of Blazor WebAssembly will have many states. A component lifecycle begins when the component is navigated to or it is used in another component. At some point, the instance of the component will be discarded. Blazor WebAssembly provides hooks for you to interfere with the process of each state of a component. This guide will introduce all the states of a component and their order.

You can download the example code used in this topic on GitHub.

Introduction to lifecycle hook

A lifecycle hook is a method that is fired when a component is switching its state. For example, from non-existent to initialized, from initialized to parameters set. The following image illustrates the lifecycle sequence of a component, from start to finish.

The lifecycle of a component begins with OnInitialized method and ends with Dispose method. To have Dispose method in your component, you will need to implement the IDisposable by using the directive @implement in the directive section of the component.

The following table illustrates all the hooking methods and their purposes in sequence from the component is created to being disposed.

Hook method Purpose
OnInitialized() This method is called right after Blazor WebAssembly rendered the component.
OnInitializedAsync() Same as OnInitialized but for async operations.
OnParametersSet() Respond to property with [Parameter] attribute changes.
OnParametersSetAsync() Same as OnParametersSet() but for async operations.
OnAfterRender(true) This method is called right after the component is rendered, initialized and has its parameters set.
OnAfterRenderAsync(true) Same as OnAfterRender(true) but for async operations.
OnAfterRender(false) Response to the StateHasChanged() method.
OnAfterRenderAsync(false) Same as OnAfterRender(false) but for async operations.
Dispose() To use this method, the component must have @implements IDisposable directive. Otherwise, it is just a normal method and will not be called by Blazor WebAssembly. This method responds to clean up the component.

Lifecycle example

The following example illustrates the lifecycle of a component. First, the component is not rendered. When you click on the Toggle button, the component will be rendered, thus triggering the hook methods in sequence. When you click on the Toggle button again, the component is removed and triggering the Dispose method.

Main phases of a component

In the previous section, you have learned the hooking methods sequence. In summary, Blazor WebAssembly components have 4 main phases: Initialize, ParametersSet, AfterRender and Dispose. Each phase has 2 hooking methods for synchronous and asynchronous operations except Dispose phase only has a hooking method for synchronous operations. We will go through all of the phases one by one in the next sections.


Initialize and Dispose phase

Initialize is the first phase of a component. This phase has 2 hooking methods: OnInitialized and OnInitializedAsync for both synchronous and asynchronous tasks. In this phase, you can:

  • Perform fetching data from the API.
  • Register for events.
  • Set the default value for the properties.
  • Execute JavaScript.

Our InitializeAndDispose.razor demonstrates some tasks you can do in the Initialize phase.

protected override async Task OnInitializedAsync()
{
    await JSRuntime.InvokeVoidAsync("alert", "Blazor School");
    Company = new()
    {
        Name = "DotNetPro"
    };
    NavigationManager.LocationChanged += OnLocationChanged;
    ProductName = await HttpClient.GetStringAsync("/sample-data/product.txt");
}

Clean up resources after use

To avoid memory leaks, improve performance and avoid unwanted results, you need to clean up resources after use. Dispose is the phase to free resources that won't be collected automatically. To have your component dispose correctly, you need to use @implement directive to implement IDisposable interface. Then put cleanup code logic in Dispose() method. Blazor WebAssembly will automatically call the Dispose() method when needed.

In this phase, you need to:

  • Unsubscribe from events.
  • Stop working tasks.
  • Close opening stream.

Our InitializeAndDispose.razor demonstrates how to unsubscribe from an event.

public void Dispose()
{
    NavigationManager.LocationChanged -= OnLocationChanged;
}

ParametersSet phase

Once the component has been initialized, it will switch to ParametersSet phase. In this phase, you can reactive to the changes from the parent component or from the parameters changed in the url (it looks like the LocationChanged event from NavigationManager but they are 2 different triggers). The following image illustrates how ParametersSet phase is triggered.

Our ParametersSet.razorshows how to pass a parameter to the CompanyDetail.razor component and has a method to change its value.

@foreach (var company in Companies)
{
    <CompanyDetail Company="company"></CompanyDetail>
}
<button class="btn btn-primary" @onclick="UpdateCompanyName">Update Company Name</button>

@code {
    private List<Company> Companies { get; set; } = new()
    {
        new()
        {
            Name = "DotNetPro"
        },
        new()
        {
            Name = "Microsoft"
        }
    };

    private void UpdateCompanyName()
    {
        Companies[0].Name = "DotNetPro Technology";
        Companies[1].Name = "Microsoft Corporation";
    }
}

Our CompanyDetail.razor component shows how to receive the parameter from the parent and how to use the hooking methods to react when it changes.

@inject IJSRuntime JSRuntime 

<h3>@Company.Name</h3>

@code {
    [Parameter]
    public Company Company { get; set; }

    protected override async Task OnParametersSetAsync()
    {
        await JSRuntime.InvokeVoidAsync("alert", "Parent changes values");
    }
}

AfterRender phase

Like the hooking methods of ParametersSet phase, AfterRender hooking methods to react to changes. Instead of reacting to parameters change as ParametersSet phase, AfterRender hooking methods react to StateHasChanged() method. Whenever StateHasChanged() called by the current component itself or from the parent component, the hooking methods of AfterRender are fired. The following image illustrates how AfterRender phase triggered.

Our AfterRender.razor component demonstrate how to trigger AfterRender hooking methods and how to react when triggered.

@inject IJSRuntime JSRuntime

<button class="btn btn-primary" @onclick="_ => StateHasChanged()">Trigger AfterRender</button>

@code {
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await JSRuntime.InvokeVoidAsync("alert", $"AfterRender phase triggered with firstRender is {firstRender}");
    }
}
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-2025 Blazor School
An unhandled error has occurred. Reload 🗙