CoCo
CoCo

Reputation: 217

What is the difference between SetParametersAsync and OnParametersSet method in Blazor lifecycle?

I have created one Blazor web application. In that when the child component receives the values from the parent component using a [parameter], both OnparametersSet and SetparametersAsync methods are triggered. I just want to know the difference between OnparametersSet and SetparametersAsync methods. When SetParametersAsync method gets triggered and when the OnParametersSet method gets triggered?

Upvotes: 9

Views: 8267

Answers (1)

Henk Holterman
Henk Holterman

Reputation: 273169

SetParametersAsync() is called first when a component is (re-)rendered. The base implementation actually sets the parameters.

OnParametersSet() is also called every time a component is (re-)rendered but after SetParametersAsync() and after OnInitialized{Async}().

You override SetParametersAsync() when you want to manually set the parameters. This can be an optimization. But be careful, do not await anything here.

You override OnParametersSet() to react to the new parameter values. Like fetching new data. The base implementation does nothing.

This picture is from the docs but it is wrong where it places SetParametersAsync in the "-First render only-" section:

https://learn.microsoft.com/en-us/aspnet/core/blazor/components/lifecycle

Source: https://learn.microsoft.com/en-us/aspnet/core/blazor/components/lifecycle

Upvotes: 7

Related Questions