.NET › Blazor (Server & WebAssembly)
What are Blazor component lifecycle methods, and what is the purpose of OnInitializedAsync versus OnParametersSetAsync?
IntermediateAnswer
OnInitializedAsync runs once when the component is first created, ideal for initial data loading. OnParametersSetAsync runs every time the component receives new parameter values from its parent (including the very first time, after OnInitializedAsync), useful for reacting to changing inputs -- e.g., a component displaying details for an Id parameter should re-fetch data in OnParametersSetAsync if the Id can change without the component being recreated.
@code {
[Parameter] public int UserId { get; set; }
private User? user;
protected override async Task OnParametersSetAsync() {
user = await UserService.GetUserAsync(UserId); // re-runs if UserId changes
}
}Real-world example A user-detail component correctly refetches data whenever its parent navigates to a different user's Id by implementing OnParametersSetAsync instead of OnInitializedAsync, which would only load data once and never update on subsequent Id changes.