简体   繁体   中英

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

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"?

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:

在此处输入图片说明

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

在此处输入图片说明

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM