Component Lifecycle

A lifecycle of a component starts when the component being rendered and ends when the component being removed from the UI. Component has 4 main phases: Initialize, ParametersSet, AfterRender and Dispose. Each phase has hooking methods with different purpose, allows you to manipulate your component dynamically.

This tutorial includes:

  • Phases and lifecycle hooks
  • Initialize and Dispose phase.
  • ParametersSet phase.
  • AfterRender phase.
You can download the example code used in this topic on GitHub.

Phases and lifecycle hook methods

A component in Blazor Server has 4 main phases: Initialize, ParametersSet, AfterRender and Dispose. Each phase will have 2 hook methods for synchronous and asynchronous operations, except Dispose phase which only has 1 hook method. The following image demonstrates the order of those lifecycle method hooks:

blazor-server-component-lifecycle-methods.png

Dispose is not a default hook method. To enable this hook method, your component needs to implement the IDisposable interface.

The following table illustrates the purpose and execute order of each hook method:

Hook method Execute sequence Purpose
OnInitialized() 1 This method is called right after Blazor Server rendered the component.
OnInitializedAsync() 2 Same as OnInitialized but for async operations.
OnParametersSet() 3 and on demand Respond to property with [Parameter] attribute changes.
OnParametersSetAsync() 4 and on demand Same as OnParametersSet() but for async operations.
OnAfterRender() 5 and on demand Response to the StateHasChanged() method.
OnAfterRenderAsync() 6 and on demand Same as OnAfterRender() but for async operations.
Dispose() On demand Clean up the component.

The following video illustrates a lifecycle of a component:

First, the component is not rendered, the lifecycle of the component does not start. Next, the component is rendered. As a result, the lifecycle starts and you can see the component lifecycle changing its state to Initialize, ParametersSet and then AfterRender. Finally, when the component is removed from the UI, the hook method Dispose is called as the component is being disposed.


Initialize and Dispose phase

A component lifecycle starts with Initialize phase and ends with Dispose phase. In the Initialize phase, a few examples that you can do:
  • Perform fetching data from the API.
  • Subscribe events.
  • Set the default values for properties.
  • Execute JavaScript.

Free resources after use

This step is usually ignored as it is not required by the framework. Ignoring this step can greatly impact the performance and causes some unwanted results. Some resources can be automatically collected by GC, some are not. You need to:

  • Unsubscribe events.
  • Stop working tasks.
  • Close opening streams.

To make your component dispose correctly, you need to use @implement directive and implements the IDisposable interface. Then declare a public void Dispose() method to free the resources. Here is an example code for Initialize and Dispose phase:

@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;
}

ParametersSet phase

In this phase, you can react to the parameter changes. The parameters change can come from the parent component or the URL. The following image illustrate how ParametersSet phase is triggered.

paramters-set-phase.png

React to parent component changes

ParametersSet phase can be used to react to the changes that comes 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 the example, ComponentParameter is a parameter which being passed from the parent component. When the original value in the parent component changes, the child component will trigger 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 phase

Each time Blazor renders the UI, AfterRender phase is triggered. In the AfterRender phase, a few examples that you can do:

  • Trigger 3rd party to format UI.
  • Collect user's behaviours.
@inject IJSRuntime JSRuntime

<h3>AfterRender</h3>
<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}");
}

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-2025 Blazor School
An unhandled error has occurred. Reload 🗙