Telerik blogs

Component rendering is a core mechanic of Blazor applications turning C# components into HTML and CSS. Lifecycle methods allow us to execute custom code synchronously or asynchronously.

Blazor applications consist of a tree of Blazor components that build an interactive user interface. Rendering starts atop the tree and flows down to each component’s children.

The reason for rendering the component hierarchy top-down is that the parent component decides what child components are created.

In this article, we learn how Blazor renders components and how to inject custom code into the component lifecycle.

Blazor Component Lifecycle Methods

The rendering process cannot be interrupted; otherwise, the user interface would not be responsive.

That’s why Blazor components use lifecycle methods to allow for code execution during a component’s lifetime. A lifecycle method is called when a specific event during the component’s lifetime is triggered.

A Blazor component is rendered for the first time after its instance is created when included as a child component.

A diagram with the parent component at the top. The parent component triggers the child component creation. The SetParametersAsync lifecycle method and the OnInitialized(Async) methods are triggered only for the first render. The OnParametersSet(Async) method is triggered when the parent component provides a different parameter to its child component. The StateHasChanged method can be used by the developer to trigger a manual rerender of the component.

The SetParametersAsync Lifecycle Method

The first callback method in the component lifecycle is the SetParametersAsync method. It gets the parameters provided by the parent component.

By overriding the SetParametersAsync method, we can use custom code to change the values the parent component provides.

With the default implementation, the parameters will be set to the properties decorated with the Parameter attribute. If we want to use the component parameters differently, we can use custom code and override the SetParametersAsync method to define the desired behavior.

@code {
    private int TitleLength = 0;

    [Parameter]
    public string? Title { get; set; }

    public override async Task SetParametersAsync(ParameterView parameters)
    {
        if (parameters.TryGetValue<string>(nameof(Title), out var value))
        {
            if (value is null)
            {
                TitleLength = 0;
            }
            else
            {
                TitleLength = Title.Length;
            }
        }

        await base.SetParametersAsync(parameters);
    }
}

The SetParametersAsync lifecycle method is only called for the first render of a Blazor component.

OnInitialized & OnInitializedAsync Lifecycle Methods

After the Blazor component completes the execution of the SetParametersAsync method and, therefore, all the parameters from the parent component are set, the OnInitialized and OnInitializedAsync lifecycle methods are called.

The OnInitialized and OnInitializedAsync methods are the perfect place to load data from the database and assign it to properties used in the component’s template.

@code {
    private string? message;

    [Parameter]
    public string Name { get; set; }

    protected override void OnInitialized()
    {
        message = $"Welcome, {Name}!";
    }
}

As shown in this example, we can also use the values received as a component parameter within the synchronous OnInitialized lifecycle method.

The OnParametersSet & OnParametersSetAsync Lifecycle Methods

The SetParametersAsync is only called the first time a Blazor component is rendered.

However, the OnParametersSet and OnParametersSetAsync lifecycle methods are triggered whenever the parent component re-renders, providing a different value for a child component’s parameters.

Overriding those methods provides us access to update values in the component based on a new set of parameters.

@code {
    private string? message;

    [Parameter]
    public string Name { get; set; }

    protected override void OnParametersSet()
    {
        message = $"Welcome, {Name}!";
    }
}

After the OnParametersSet or OnParametersSetAsync lifecycle methods have been completed, an automatic re-rendering of the component is triggered.

The StateHasChanged Method

We can call the StateHasChanged method of the ComponentBase class to let the Blazor component know that the component state has changed.

The StateHasChanged method will trigger a component re-render, which will call all applicable lifecycle methods during the rendering process.

However, you should not call the StateHasChanged method in the following scenarios:

  • Event Handling. It doesn’t matter if the events are synchronous or asynchronous. The ComponentBase class triggers a render for most event handlers.
  • Implementing lifecycle methods such as OnParametersSetAsync or OnInitialized (synchronous or asynchronous). The ComponentBase class triggers a render for most lifecycle events.

As a general rule of thumb: Usually, you don’t need to call the StateHasChanged method manually. However, if you expect the user interface to show an updated value and it doesn’t, chances are high that a StateHasChanged call at the right place will fix your issue.

Read more about edge cases where calling StateHasChanged is required to get the desired behavior in the ASP.NET Core Razor Component Rendering documentation.

Asynchronous vs. Synchronous Lifecycle Methods

For synchronous code, parent components are always rendered before child components.

Asynchronous code gets more complicated. When using asynchronous lifecycle methods, the completion order of a parent and child component isn’t deterministic because it relies on the initialization code.

However, Blazor ensures component parameters are available and correctly updated when rendering a child component.

This raises the question: Should you use synchronous or asynchronous lifecycle methods to implement Blazor components?

So far, it has worked best for me to use synchronous lifecycle methods when I do not need to await asynchronous operations.

Whenever I need to call the database or use other asynchronous operations, I must use the asynchronous callback methods. However, if that’s not the case, I use the more straightforward synchronous callback methods.

Conclusion

Blazor components use lifecycle methods to prevent user interface blocking and allow developers to execute custom code.

The SetParametersAsync method allows the execution of custom code handling the parameters provided by the parent component and is only executed for the first render of a Blazor component.

The OnInitialized and OnInitializedAsync lifecycle methods are often used to load data from the database or to initialize properties rendered as part of the component’s template.

The OnParametersSet and OnParametersSetAsync lifecycle methods are called whenever the parent component is re-rendered, providing another parameter to the child component.

If the user interface isn’t showing the expected value on the screen, you may miss a StateHasChanged call at the appropriate place in your code.

There are synchronous and asynchronous lifecycle methods. Use the method appropriate for your context. Start with synchronous and use asynchronous if you have to perform asynchronous operations such as reading data from the database or calling a remote API.

This article summarizes and explains the fundamentals of Blazor component lifecycle handling. If you want to dive deep and learn the ins and out, you will find more information in the Blazor lifecycle documentation.


About the Author

Claudio Bernasconi

Claudio Bernasconi is a passionate software engineer and content creator writing articles and running a .NET developer YouTube channel. He has more than 10 years of experience as a .NET developer and loves sharing his knowledge about Blazor and other .NET topics with the community.

Related Posts

Comments

Comments are disabled in preview mode.