I have a simple Blazor component.
<div @onclick="HandleClick">Click me</div>
@code {
public async Task HandleClick()
{
await Task.Run(()=> System.Threading.Thread.Sleep(1000));
}
protected override void OnAfterRender(bool firstRender)
{
Console.WriteLine("Rendered");
}
}
When I click on the div "Rendered" is printed to console and after 1 sec again which means that blazor has rendered component twice. I understand that Blazor triggers an automatic re-render of a component as part of dispatching an event to it.
But why does it rerender after the task is completed? How can I avoid second render?
I have some JS interop in OnAfterRender lifecycle hook that now runs twice. I can add some sort of counter but that would polute my code and I would like to avoid that.
I my HandleClick
were a simple public void method then everything is ok but that is not always possible
await Task.Run
, take a look to: stackoverflow.com/questions/56604886/… – dani herrera