I am now using SetParametersAsync() for a [Parameter] that is not set when OnInitializedAsync() is called. But that led to my thinking…
Even a property as simple as Visible, while usually set to "true" or "false" could sometimes be set based on a DB query and therefore get set after OnInitializedAsync() is called.
So… should I handle every [Parameter] only in SetParametersAsync() and not in OnInitializedAsync()
Or, should I handle them in OnInitializedAsync() if they’re non-null and also watch for them being changed in SetParametersAsync()
And associated question. For each parameter I handle in SetParametersAsync(), do I need to keep a local copy of what it was last set to, to determine if the new value is a change? Or is there a way I can ask ParameterView if the value is changed? (I can’t find anything in my searching.)
This is a difficult question (did it change) as in this case, it’s a List and so getting a "new value where list.Count == prevList.Count does not mean that the list didn’t change.
>Solution :
I use the following rule of thumb:
OnInitialized-:
Here I will get things ready for the component, and very rarely do anything related to component parameters. Very often I will set internal or private parameters/fields for UI based logic or other defaults not set on the parameter/field. Things like rendering of a loading modal, EditContext etc. If I have a component that does not have parameters, I will add all starting logic here.
OnParameterSet-:
Here I will add all my component parameter logic and do hash checking to identify whether a parameter updated. Useful when working with your List<T> example and it’s much cheaper storing a hash string instead of a whole list.
OnAfterRender-:
I usually reserve this for JavaScript. In my ~4 years of Blazor, I’ve only called JavaScript here.