Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does StateHasChanged re-render all the component or only the differences?

Tags:

c#

blazor

I am learning Blazor Component and I am wondering about StateHasChanged force the component to re-render all itself or only the differences. The intellisense report that

Notifies the component that its state has changed. When applicable, this will cause the component to be re-rendered.

What it means with "this will cause the component to be re-rendered"?

like image 363
Leonardo Lurci Avatar asked Dec 17 '22 14:12

Leonardo Lurci


1 Answers

StateHasChanged will cause only the differences to be re-rendered.

To prove that, I've created the following Blazor component that has 2 buttons:

  • first button generates a list of 10 000 <li> elements, numbered 0 .. 9999
  • second button modifies the value of the first <li> and calls StateHasChanged()

Here is the complete code:

@page "/BigDataStateHasChanged"

<h3>BigDataStateHasChanged</h3>

<button class="btn btn-primary" @onclick="GenerateBigData">Generate big data</button>
<button class="btn btn-primary" @onclick="ChangeOneRow">Change 1 row</button>

@if(list != null)
{
    @foreach(var item in list)
    {
        <li>@item</li>
    }
}

@code {
    List<int> list;
    const int cMaxNumbers = 10000;

    protected void GenerateBigData()
    {
        list = new List<int>(cMaxNumbers);
        for(int i = 0; i < cMaxNumbers; i++)
        {
            list.Add(i);
        }
    }

    protected void ChangeOneRow()
    {
        list[0] = 123456;
        StateHasChanged();
    }
}


I then used the Chrome's development tools to monitor the websockets. On the Network tab, when clicking on the first button, I can see that 1.4 MB was transferred via the websockets to the client:

enter image description here

Then, after clicking the second button that only changes the first element, I can see that only 153 bytes have been transferred:

enter image description here

So, from this, the conclusion is that only the "diff" gets rendered.

like image 93
rk72 Avatar answered Dec 24 '22 02:12

rk72