Blazor cascading values performance
In this video we will discuss the performance aspect of Blazor cascading values.
CascadingValue component has IsFixed
boolean property. The default value of this property is false
. This means the value that is cascaded down the component tree is constantly monitored by Blazor. When the cascaded value changes all the components in the entire component tree, that use the cascaded value are automatically updated. However, this constant monitoring requires resources and it is better to turn of this active monitoring when it is not required to avoid performance issues.
When to turn off monitoring cascading values
- To turn off monitoring cascading values set IsFixed boolean property to true.
- In this example the color is set to red and it never changes again.
- So, it makes sense to turn off monitoring the cascading value.
ParentComponent.razor
<h1 style="@Style">Parent Component Text</h1>
<CascadingValue Value="@Style" Name="ColorStyle" IsFixed="true">
<ChildComponent></ChildComponent>
</CascadingValue>
@code {
public string Style { get; set; } = "color:red";
}
ChildComponent.razor
<h1 style="@ElementStyle">-Child Component Text</h1>
@code {
[CascadingParameter(Name = "ColorStyle")]
public string ElementStyle { get; set; }
}
When not to turn off monitoring cascading values
- The
Counter
value is cascaded down the component tree. - The
Counter
value is increased by 1, everytimeIncrement Counter
button is clicked. - If
IsFixed
property is set totrue
, the changed value will not be cascaded down the component tree. - So in this example, it does not make sense to turn off monitoring cascading values.
ParentComponent.razor
<button class="btn btn-primary" @onclick="IncrementCounter">
Increment Counter
</button>
<h1>Parent Component Text - @Counter</h1>
<CascadingValue Value="@Counter" Name="Counter" IsFixed="false">
<ChildComponent></ChildComponent>
</CascadingValue>
@code {
public int Counter { get; set; } = 0;
private void IncrementCounter()
{
Counter = Counter + 1;
}
}
ChildComponent.razor
<h1>Child Component Text - @Counter</h1>
@code {
[CascadingParameter(Name = "Counter")]
public int Counter { get; set; }
}
© 2020 Pragimtech. All Rights Reserved.