How is Blazor UI notified when the property value is changed?

Platform: Blazor| Category: General

Blazor notifies the UI changes automatically whenever the bound property is changed in a button click, input text, dropdown, etc.Blazor triggers the StateHasChanged() method to notify the change. However, there are some exceptional cases where the user has to manually call the StateHasChanged() method to notify that the UI has been updated. 

By calling the StateHasChanged(), Blazor can manually be notified when to rerender its UI. This method will tell Blazor when to refresh the UI.

@using System.Threading;

<h1>@Count</h1>

<button @onclick=@StartCountdown>Start Timer</button>

@functions {
    private int Count { get; set; } = 10;

    void StartCountdown()
    {
        var timer = new Timer(new TimerCallback(_ =>
        {
            if (Count > 0)
            {
                Count--;

                // Note that the following line is necessary because otherwise
                // Blazor would not recognize the state change and refresh the UI
                InvokeAsync(() =>
                {
                    StateHasChanged();
                });
            }
        }), null, 1000, 1000);
    }
}

In the above example, when the button is clicked, the UI will refresh for every count down of the timer since StateHasChanged method has been called to refresh the UI.

Share with

Related FAQs

Couldn't find the FAQs you're looking for?

Please submit your question and answer.