In this lesson, you will learn how to hook into the lifecycle of a Blazor component to manage initialization logic and react to property changes.
Understanding the Component Lifecycle
In Blazor, a component isn't just a static piece of HTML; it is a C# class that moves through various stages of existence. To control what happens when a component is first created or when its configuration changes, we use lifecycle methods.
Initialization with OnInitialized
The OnInitialized method (and its asynchronous counterpart, OnInitializedAsync) is triggered exactly once when the component is first instantiated and its initial parameters have been set. This is the perfect place to fetch data from a service, set up default values, or perform one-time configuration.
protected override void OnInitialized()
{
// Fetch data from a service when the component loads
myData = service.GetData();
}
Reacting with OnParametersSet
While OnInitialized runs only once, OnParametersSet runs every time the parent component provides new values to this component. If your component needs to re-process data or reset a local state whenever a parameter changes, this is where that logic belongs.
[Parameter] public int UserId { get; set; }
protected override void OnParametersSet()
{
// Re-fetch user details whenever the UserId parameter changes
userProfile = service.LoadProfile(UserId);
}
The Difference in Practice
Think of OnInitialized as the "constructor logic" for your component's business state, while OnParametersSet is your "listener" for updates.
If you attempt to perform expensive operations inside OnParametersSet, keep in mind it runs during every render cycle where parameters are refreshed. For initial setup, always prefer OnInitialized to avoid redundant calls. By splitting your logic between these two methods, you ensure your component stays responsive and performs only the necessary work when the state actually shifts.
Key Takeaway: Use OnInitialized for one-time setup tasks and OnParametersSet to handle updates whenever a parent component passes new data into your component.