C# Blazor onParametersSetAsync is being called eventhough params has not been changed

Viewed 5591

I'm trying to figure out how Blazor behaves. I'm debugging something but temporarily removing commenting out other codes so as not to be destructed and make sure with what I am observing. The codes looks like this.

<OneComponent @ref="_oneComponent" param1="@varParam1" param2="@varParam2"></OneComponent>
@code {
  private OneComponent _oneComponent; 
  private _objectOne varParam1;   // There are values here.
  private _objectTwo varparams2;  // There are values here as well.

  private async Task SaveClicked()
  {
    if (_oneComponent.OnSaveClicked())
    {
      // nothing here.
    }
  }
}

When I run the program, I noticed the OnParametersSetAsync() of <OneComponent/> is being re-run. My question is, why would the OnParametersSetAsync() is being re-run again eventhough I didn't change any of varParam1, varParam2? Is that what it is? Should it re-run when the program now points to that component after the _oneComponent returns true or false?

2 Answers

Whether OnParametersSet() or OnParametersSetAsync() are called depends on the type of the parameters of the component.

For primitive types and also for a couple of additional types that are known to be immutable, Blazor can easily detect if the values of the parameters changed or not, and decide to call or not call the OnParametersSet() method.

So, if your parameters are bool, int, string, decimal and DateTime types, the detection works fine out of the box and OnParametersSet() will not be called unless the value of the parameters have changed.

For enum parameters or for more complex parameters, OnParametersSet() is called each time when the parent component (or page) re-renders.

This is also documented in the official Blazor docs here: https://docs.microsoft.com/en-us/aspnet/core/blazor/components/lifecycle?view=aspnetcore-3.1#after-parameters-are-set

In your code, you can write simple checks to see whether the actual value of the component's parameters changed, and only call your processing in case of the detected change.

I found out that I can use the ShouldRender() lifecycle to restrict it from being re-run.

protected override bool ShouldRender()
{
   return false;
}

The OnParametersSetAsync() is being re-run twice again as it calls the OnSaveClicked().

Related