I'm doing some tests with DotNet 5rc1 and Blazor, and have noticed something that makes me think I'm not doing this right.
I have a demo page (code below) that gives the user a set of buttons and they can click on a button to do a die roll. In the client side C# I then roll the die and prepend the roll string to a list. In the template, I then do a foreach and render the user's past rolls.
The issue is that I've been watching the Websocket messages and each time I add a new element, the message being passed gets larger and larger. This is because the entire list is being re-rendered with each click.
Is there a better way to do this, so that Blazor only inserts the new item in the DOM and sends down a trivial message, rather than re-rendering the entire section of the page? For this example, it doesn't matter much, but if I were building a bigger app with a lot of interactions, I could see this becoming a bottleneck.
Here's the code for my page - this is just a new page in a brand new Blazor project. (My code has more than a 1d20 button, but I removed it from here for brevity.)
@page "/dieroller"
<h1>Die Roller Utility</h1>
...
<button class="btn btn-primary" @onclick="@(e => RollDie(20))">
<i class="fas fa-dice-d20"></i>
</button>
<h2 class='mt-5'>Your Roll History</h2>
@foreach (string roll in rolls) {
<p>@roll</p>
}
@code {
@using System.Threading;
private List<string> rolls = new List<string>();
private void RollDie(int upper)
{
Random rand = new Random();
rolls.Insert(0, string.Format("1d{0} = {1}", upper, rand.Next(1, upper)));
}
}