Component Lifecycle Methods
When you create a component in Blazor it should derive from ComponentBase
. There are two reasons for this.
First, is that ComponentBase
implements IComponent
and Blazor uses this interface to locate components throughout your project. It doesn’t rely on a folder convention. Second, is that ComponentBase
contains important lifecycle methods, let’s take a look at what those are.
OnInitialized() / OnInitializedAsync()
Once the component has received its initial parameters from its parent in the render tree, the OnInitialized
and OnInitialized
Async methods are called.
OnInitialized
is called first, then OnInitialized
Async. Any asynchronous operations, which require the component to re-render once they complete, should be placed in the OnInitializedAsync
method.
Both of these methods will only fire once in the components lifecycle, as apposed the other lifecycle methods which will fire every time the component is re-rendered.
Example```html
@code {
private string Title { get; set; }
private string TimeRendered { get; set; }
protected override void OnInitialized()
{
Title = "Hello World";
TimeRendered = DateTime.Now.ToShortTimeString();
}
}
Example```html
@inject IBudgetService BudgetService
<h1>View Expenses Async</h1>
@if (Expenses == null)
{
<p>Loading...</p>
}
else
{
<table>
@foreach (var expense in expenses)
{
<tr>
<td>
@expense.Description
</td>
<td>
@expense.Amount
</td>
</tr>
}
</table>
}
@code {
private Expense[] expenses;
protected override async Task OnInitializedAsync()
{
expense = await BudgetService.GetExpensesAsync();
}
}
OnParametersSet() / OnParametersSetAsync()
The OnParametersSet
and OnParametersSetAsync
methods are called when a component is first initialised and each time new or updated parameters are received from the parent in the render tree.
Example```html
<button @onclick="@IncrementCounter">Increment
@code {
int CounterValue = 0;
void IncrementCounter()
{
CounterValue = CounterValue += 2;
}
}
```html
<!-- Child Component -->
@counterOutput
@code {
[Parameter] public int Counter { get; set; }
private string counterOutput;
protected override void OnParametersSet()
{
counterOutput = Counter.ToString() + " and counting...";
}
}
OnAfterRender / OnAfterRenderAsync
The OnAfterRender
and OnAfterRenderAsync
methods are called after each render of the component. At the point they are called you can expect that all element and component references are populated. This is also the place to put any JavaScript Interop calls when using server-side Blazor.
This means that if you need to perform an action, such as attaching an event listener, which requires the elements of the component to be rendered in the DOM. Then these methods are where you can do it. Another great use for these lifecycle methods are for JavaScript library initialisation, which require DOM elements to be in place to work.
Misc
While the next couple of methods aren’t part of a components lifecycle they are very closely related to it, so I wanted to briefly cover them. These methods are ShouldRender
and StateHasChanged
.
ShouldRender()
This method returns a boolean to indicate if a components UI can be rendered. However, it’s only called after the initial render of a component. Meaning even if it returns false, the component will still render once . This is mentioned by Steve Sanderson in this GitHub issue.
StateHasChanged()
This method notifies the component that its state has changed and queues a re-render. It’s called after any lifecycle method has been called and can also be invoked manually to trigger a re-render.
This method looks at the value returned from ShouldRender
to decide if a re-render should happen. However, as mentioned before, this only happens after the component has been rendered for the first time.
Summary
In this post, we’ve covered the various lifecycle methods available in Blazor. These are OnInitialized
/OnInitializedAsync
, OnParametersSet
/OnParametersSetAsync
and OnAfterRender
/OnAfterRenderAsync
.
We also had a brief look at two methods which are closely related to Blazor component lifecycle, ShouldRender
and StateHasChanged
.