Suppress UI refreshing in Blazor using ShouldRender

Last Updated on November 27, 2024

@page "/control-render"

<label>
    <input type="checkbox" @bind="shouldRender" />
    Should Render?
</label>

<p>Current count: @currentCount</p>

<p>
    <button @onclick="IncrementCount">Click me</button>
</p>

@code {
    private int currentCount = 0;
    private bool shouldRender = true;

    protected override bool ShouldRender()
    {
        return shouldRender;
    }

    private void IncrementCount()
    {
        currentCount++;
    }
}

ShouldRender is called each time a component is rendered. Override ShouldRender to manage UI refreshing. If the implementation returns true, the UI is refreshed.

Even if ShouldRender is overridden, the component is always initially rendered.

private bool _shouldRender = true;
protected override bool ShouldRender()
{
    return _shouldRender;
}
private async void ToolbarItemEditPointOnClick()
{
    _shouldRender = false; // Disable rendering

    // Do something here

    _shouldRender = true; // Re-enable rendering
    await InvokeAsync(StateHasChanged); // Trigger manual rendering
}

References
https://docs.microsoft.com/en-us/aspnet/core/blazor/components/rendering?view=aspnetcore-6.0#suppress-ui-refreshing-shouldrender
https://www.syncfusion.com/faq/how-do-i-suppress-the-ui-rendering-in-blazor