Different Blazor Lifecycle Events

Different lifecycle events are available in Blazor, which we can use based on our requirements. Today, we discuss some of the important events. All the lifecycle events are virtual; we need to override them to use them.

 

OnInitializedAsync: This is the first event in the Blazor life cycle. To load the data, OnInitializedAsync() is the best place to have all database-related call codes. By this event, the UI has not been rendered. OnInitializedAsync is for async operations like long-running tasks. We also have OnInitialized() for sync operations. The OnInitialized() event will get fired, followed by the OnInitializedAsync() event. These events will be executed only once.

 

OnParameterSetAsync: OnParameterSetAsync() will be fired when the Blazor component is initialised and after the OnInitialized event. It will also be fired when any of the input parameter values change. The OnParameterSetAsync() event has a corresponding sync event, OnParameterSet().

 

We can have the code in the OnParameterSetAsync() event, which depends on the input parameters.

 

OnAfterRenderAsync: This event will be called after the component renders. That means all elements will be rendered by the time of the OnAfterRenderAsync event. So, this event is the best place to have any Javascript-related code. The OnAfterRenderAsync() event also has its corresponding sync event, OnAfterRender(). OnAfterRenderAsync() and OnAfterRender() expect the input parameter firstRender, which returns true on the first render and false for other renders.