SharpRuneOpen playground

Events, state and re-rendering

Handle clicks with methods, lambdas and async handlers, raise EventCallback from child to parent, and know when StateHasChanged is needed.

  • 30 min
  • Read, predict, then run
Blazor WebAssembly project

In the SharpRune app for iPhone and iPad, tap Run in Preview: the app compiles the Razor components on the device and runs the project on .NET 9. On a computer, download the project and run it with the .NET 9 SDK. The separate C# companion practice below runs in this browser.

At a glance

What makes Home render

TriggerRendersScreen afterwards
Tap Add 1 (@onclick)1, after the handlercount=1
Tap Save (async Task)3, one via StateHasChangedChecking, Writing, Saved
Child calls OnRate with 41, of the parent Homerating=4
Timer tick0stale: seconds=0
Timer asks for a render1seconds=2

Blazor renders after its own handlers, around an await, and for the parent of an EventCallback. A timer's change shows only once it calls InvokeAsync(StateHasChanged).

From a tap to your C# method

When the Razor compiler sees @onclick="Increment", it creates an EventCallback that wraps the Increment method and remembers the component that owns it. During rendering, the button gets an event handler entry in the render tree, and Blazor's script listens for clicks on it. When you tap the button, the browser raises a click event, the script passes it to .NET with an identifier for the handler, and the renderer calls your method. In Blazor WebAssembly this round trip stays inside the browser tab; no server is involved.

After the method runs, ComponentBase calls StateHasChanged on the component that owns the handler. That rule is what makes Blazor feel automatic: you change a field in a handler, and the next render shows it. @onclick accepts a method with no parameters, a method that takes MouseEventArgs, a lambda, or a method that returns Task. A lambda is the usual way to pass an argument, as in @onclick="() => Add(amount)". Inside @foreach each lambda gets its own amount, so every button adds its own value.

Async handlers and the renders in between

A handler that returns Task can await work such as a web request or a delay. ComponentBase handles it in two steps. It starts the handler and renders as soon as the handler returns its Task. If that Task is not finished yet, which is the case once the handler awaits something unfinished, ComponentBase waits for it and renders again when it completes. That gives you two renders without any extra code: one showing the state before the first await finishes, and one showing the final state.

Anything between those two points stays invisible unless you ask for it. SaveAsync in this project sets the status to Checking…, awaits, sets Writing…, awaits again and finishes with the saved message. Without the StateHasChanged call after Writing…, you would see Checking… for the full 1.6 seconds and then the final message. Use async Task, not async void, for handlers. With async void Blazor cannot see when the work ends, so it skips the render at completion, and exceptions escape its error handling.

EventCallback: from child to parent

A child component often needs to tell its parent that something happened. RatingPicker in this project does not store the rating. It receives Value from Home, draws the stars, and reports taps through two parameters: OnRate, an EventCallback<int>, and OnClear, a plain EventCallback. Home connects them to its own methods with OnRate="SetRating" and OnClear="ClearRating". When a star is tapped, the child calls OnRate.InvokeAsync(stars).

An EventCallback is a struct that holds the delegate and a receiver: the component that created the callback, here Home. InvokeAsync runs the delegate and then lets the receiver handle it like one of its own events, so Home renders afterwards. A plain Action<int> parameter would run Home's method too, but nothing would tell Home to render, and the page would ignore the tap until some other event rendered Home. Prefer EventCallback<T> when the child passes a value, because the compiler then checks the handler's parameter type. The HasDelegate property tells the child whether the parent assigned a callback at all.

When you need StateHasChanged

Blazor renders a component after its own event handlers, after it receives new parameters and after its lifecycle methods. It cannot know about anything else. A System.Threading.Timer callback, a C# event raised by a service, or a background task that finishes later all change fields without telling the renderer. Stopwatch shows this. OnTick adds one second per tick, and the screen changes only because the callback calls InvokeAsync(StateHasChanged). Tap Stop screen updates and the callback skips that call: the field keeps counting, but the number on screen freezes. Tap Refresh, whose handler does nothing, and the number jumps to the current value, because an event caused a render.

InvokeAsync runs code on the renderer's synchronization context, which is where component state should change and where StateHasChanged may be called. In Blazor Server and in multithreaded runtimes, timer callbacks run on other threads, and calling StateHasChanged from there throws an InvalidOperationException. A single-threaded WebAssembly app may not throw, but InvokeAsync keeps the component correct wherever it runs. A component that starts a timer or subscribes to an event should implement IDisposable with @implements IDisposable and stop the timer in Dispose. Otherwise the callback keeps running after you leave the page.

Trace the page and the companion

Tap Add 1: Increment runs, ComponentBase renders Home, and the big number shows 1. Tap Add 10: the lambda calls Add(10) with the amount captured for that button. Tap Save the count: the first render disables the button and shows Checking…, StateHasChanged shows Writing…, and the completion render shows the saved message and enables the button again. Tap the fourth star: the child invokes OnRate with 4, SetRating stores it, and Home renders. The new Value parameter flows back into RatingPicker, which highlights four stars.

The console companion prints the same kind of sequence from a model of these rules. Its HandleEventAsync starts a handler, renders, and renders again if the handler was still running. The click produces one render, the save produces three, the child's callback produces one render of the parent, and the two timer ticks produce none until the model calls StateHasChanged. Read the output next to the page. The model and the app agree on when renders happen, but only the app shows that Blazor behaves this way.

Common mistakes, practice and review

Writing @onclick="Increment()" calls the method while rendering instead of passing it; for a void method the build fails. In a for loop, a lambda that uses the loop variable directly sees its final value, which is why RatingPicker copies i into stars before the button. Calling StateHasChanged at the end of every handler adds nothing, because Blazor already renders there. Forgetting to dispose a timer leaves it running after the component is gone.

To practice, remove the StateHasChanged call from SaveAsync and confirm that Writing… never appears. In a copy of RatingPicker, change OnRate to Action<int> and watch the page ignore taps until another event renders Home. Add a third callback that tells Home when the same star is tapped twice in a row. Change the timer to tick every 250 milliseconds and show tenths of a second.

Key points
  • Blazor renders a component after its own event handlers, and twice for an async handler that awaits.
  • Call StateHasChanged for middle steps of an async handler and for changes made outside Blazor events.
  • EventCallback and EventCallback<T> carry events from child to parent and render the parent afterwards.
  • Use InvokeAsync from timers and other outside callbacks, and dispose timers in Dispose.
Runs on this device: SharpRune compiles the Razor components and C# here and runs the app in Preview on .NET 9 WebAssembly. The same files run on a computer with the .NET 9 SDK and dotnet run.

Events, state and re-rendering — Blazor WebAssembly project

Run the project

  1. Tap Run in Preview. SharpRune copies these files into a new project, compiles the Razor components on this device and opens the app in Preview.
  2. Tap Add 1, Add 10 and Save the count, and watch the status line. Tap a star, then tap Start under the stopwatch.
  3. While the stopwatch runs, tap Stop screen updates, wait a few seconds, then tap Refresh.
  4. Change a .razor file and tap Run again to rebuild.
  5. On a computer: install the .NET 9 SDK, save the files with their folders, and run dotnet run in that folder.

Download the project ↗

Project files

EventsAndState.csprojDownload file ↗
EventsAndState.csproj
<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">

  <PropertyGroup>
    <TargetFramework>net9.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <AssemblyName>EventsAndState</AssemblyName>
    <RootNamespace>EventsAndState</RootNamespace>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="9.0.4" />
    <PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly.DevServer" Version="9.0.4" PrivateAssets="all" />
  </ItemGroup>

</Project>
Program.csDownload file ↗
Program.cs
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using EventsAndState;

var builder = WebAssemblyHostBuilder.CreateDefault(args);

// <App> replaces <div id="app"> in wwwroot/index.html.
builder.RootComponents.Add<App>("#app");
// HeadOutlet lets <PageTitle> set the browser tab title.
builder.RootComponents.Add<HeadOutlet>("head::after");

await builder.Build().RunAsync();
App.razorDownload file ↗
App.razor
<Router AppAssembly="@typeof(App).Assembly">
    <Found Context="routeData">
        <RouteView RouteData="@routeData" />
        <FocusOnNavigate RouteData="@routeData" Selector="h1" />
    </Found>
    <NotFound>
        <PageTitle>Not found</PageTitle>
        <h1>Not found</h1>
        <p>There is no page at this address.</p>
    </NotFound>
</Router>
_Imports.razorDownload file ↗
_Imports.razor
@using System.Net.Http
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using EventsAndState
@using EventsAndState.Components
Pages/Home.razorDownload file ↗
Pages/Home.razor
@page "/"

<PageTitle>Events and state</PageTitle>

<h1>Events and state</h1>

<section class="card">
    <h2>Click handlers</h2>
    <p class="big">@count</p>
    <div class="row">
        @* A method group: Blazor calls Increment when the button is clicked. *@
        <button class="primary" @onclick="Increment">Add 1</button>
        @* A lambda passes an argument. foreach gives every lambda its own amount. *@
        @foreach (var amount in amounts)
        {
            <button @onclick="() => Add(amount)">Add @amount</button>
        }
        <button @onclick="() => count = 0">Reset</button>
    </div>
</section>

<section class="card">
    <h2>An async handler</h2>
    <p role="status">@saveStatus</p>
    <button class="primary" @onclick="SaveAsync" disabled="@saving">Save the count</button>
</section>

<section class="card">
    <h2>From child to parent</h2>
    @* RatingPicker reports taps through EventCallback parameters. This page owns the rating. *@
    <RatingPicker Value="rating" OnRate="SetRating" OnClear="ClearRating" />
    <p>Your rating: <strong>@(rating == 0 ? "none" : $"{rating} of 5")</strong></p>
    <p class="muted">Ratings so far: @(history.Count == 0 ? "none" : string.Join(", ", history))</p>
</section>

<section class="card">
    <h2>Outside Blazor's events</h2>
    <Stopwatch />
</section>

@code {
    private int count;
    private readonly int[] amounts = [5, 10];

    private string saveStatus = "Not saved yet.";
    private bool saving;

    private int rating;
    private readonly List<int> history = [];

    // After an event handler returns, Blazor renders this component again by itself.
    private void Increment() => count++;

    private void Add(int amount) => count += amount;

    private async Task SaveAsync()
    {
        saving = true;
        saveStatus = "Checking…";
        // Blazor renders when the handler first waits on an unfinished task: "Checking…" appears.
        await Task.Delay(800);

        saveStatus = "Writing…";
        // A middle step. Blazor does not render here by itself, so ask for a render.
        StateHasChanged();
        await Task.Delay(800);

        saving = false;
        saveStatus = $"Saved a count of {count}.";
        // Blazor renders once more when the handler's task completes.
    }

    // Runs when the child invokes OnRate. Blazor renders this page afterwards.
    private void SetRating(int stars)
    {
        rating = stars;
        history.Add(stars);
    }

    private void ClearRating() => rating = 0;
}
Components/RatingPicker.razorDownload file ↗
Components/RatingPicker.razor
<div class="stars" role="group" aria-label="Rating">
    @for (var i = 1; i <= Max; i++)
    {
        // Copy the loop variable: every lambda in a for loop shares the same i.
        var stars = i;
        <button class="@(stars <= Value ? "on" : "")" aria-label="@stars of @Max" @onclick="() => OnRate.InvokeAsync(stars)">★ @stars</button>
    }
    <button class="link" @onclick="() => OnClear.InvokeAsync()">Clear</button>
</div>

@code {
    // The parent owns the value and passes it in. This component never assigns it.
    [Parameter] public int Value { get; set; }

    [Parameter] public int Max { get; set; } = 5;

    // EventCallback<int> carries a value to the parent. InvokeAsync runs the parent's method
    // and then renders the parent, because the callback remembers which component created it.
    [Parameter] public EventCallback<int> OnRate { get; set; }

    // EventCallback without a type argument: "this happened", no value.
    [Parameter] public EventCallback OnClear { get; set; }
}
Components/Stopwatch.razorDownload file ↗
Components/Stopwatch.razor
@implements IDisposable

<p class="big">@seconds s</p>
<p class="muted">Timer updates the screen: <strong>@(updateScreen ? "yes" : "no")</strong></p>
<div class="row">
    @if (timer is null)
    {
        <button class="primary" @onclick="Start">Start</button>
    }
    else
    {
        <button class="primary" @onclick="Stop">Stop</button>
    }
    <button @onclick="() => updateScreen = !updateScreen">@(updateScreen ? "Stop screen updates" : "Resume screen updates")</button>
    @* An empty handler is still an event: Blazor renders afterwards and shows the current value. *@
    <button @onclick="() => { }">Refresh</button>
</div>

@code {
    private Timer? timer;
    private int seconds;
    private bool updateScreen = true;

    private void Start() => timer = new Timer(OnTick, null, 1000, 1000);

    private void Stop()
    {
        timer?.Dispose();
        timer = null;
    }

    // The timer calls this outside Blazor's event handling. Blazor does not know
    // that seconds changed, so nothing is rendered unless the code asks for it.
    private void OnTick(object? state)
    {
        seconds++;
        if (updateScreen)
        {
            // InvokeAsync runs the code on the renderer's dispatcher.
            // StateHasChanged tells Blazor this component needs to render.
            _ = InvokeAsync(StateHasChanged);
        }
    }

    // Blazor calls Dispose when the component leaves the page. Stop the timer with it.
    public void Dispose() => timer?.Dispose();
}
wwwroot/index.htmlDownload file ↗
wwwroot/index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Events and state</title>
    <base href="/" />
    <link rel="stylesheet" href="css/app.css" />
    <link rel="stylesheet" href="EventsAndState.styles.css" />
</head>
<body>
    <div id="app">
        <p class="loading">Starting .NET…</p>
    </div>

    <div id="blazor-error-ui">
        An unhandled error has occurred.
        <a href="." class="reload">Reload</a>
        <span class="dismiss">✕</span>
    </div>

    <script src="_framework/blazor.webassembly.js"></script>
</body>
</html>
wwwroot/css/app.cssDownload file ↗
wwwroot/css/app.css
:root {
    color-scheme: light dark;
    --accent: #6b4eff;
    --line: #d8d6e4;
    --muted: #777;
}

body {
    margin: 0;
    font-family: -apple-system, system-ui, sans-serif;
    line-height: 1.5;
}

#app {
    max-width: 720px;
    margin: 0 auto;
    padding: 20px 16px 40px;
    box-sizing: border-box;
}

a, button, input, label {
    touch-action: manipulation;
}

h1 {
    font-size: 1.8rem;
    margin: 0 0 12px;
}

h1:focus {
    outline: none;
}

h2 {
    font-size: 1.15rem;
    margin: 0 0 8px;
}

.loading {
    padding: 32px 16px;
    color: var(--muted);
}

.row {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin: 12px 0;
}

input:not([type=checkbox]), select {
    font: inherit;
    padding: 8px 10px;
    border: 1px solid var(--line);
    border-radius: 8px;
    min-width: 0;
    background: transparent;
    color: inherit;
}

button {
    font: inherit;
    padding: 8px 14px;
    border-radius: 8px;
    border: 1px solid var(--line);
    background: transparent;
    color: inherit;
}

button.primary {
    background: var(--accent);
    border-color: var(--accent);
    color: #fff;
}

button:disabled {
    opacity: 0.45;
}

button.link {
    border: none;
    color: var(--accent);
    padding: 4px 6px;
}

.muted {
    color: var(--muted);
}

.card {
    border: 1px solid var(--line);
    border-radius: 12px;
    padding: 14px 16px;
    margin: 16px 0;
}

.card > :last-child {
    margin-bottom: 0;
}

code {
    font-family: ui-monospace, Menlo, monospace;
    font-size: 0.9em;
    overflow-wrap: anywhere;
}

.big {
    font-size: 2rem;
    font-weight: 700;
    margin: 4px 0;
    font-variant-numeric: tabular-nums;
}

.stars {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
    margin: 8px 0;
}

.stars button {
    padding: 6px 10px;
}

.stars button.on {
    background: #f5b301;
    border-color: #f5b301;
    color: #222;
}

#blazor-error-ui {
    display: none;
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 12px 16px;
    background: #ffe8a3;
    color: #222;
}

Expected result

The add buttons change the big number at once. Save the count disables its button and shows Checking…, then Writing…, then "Saved a count of N." about 1.6 seconds later. Tapping a star highlights the stars up to that number, shows "Your rating: N of 5" and adds N to Ratings so far; Clear sets the rating to none and keeps the history. Start counts seconds once per second. After Stop screen updates the number on screen stops changing while the timer keeps counting; Refresh jumps it to the current value. Stop ends the timer.

The project runs in the SharpRune app and with the .NET 9 SDK. Open C# practice runs the separate portable exercise.

C# companion practice

Program.cs
using System;
using System.Linq;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;

// A small model of the rules ComponentBase follows. No Blazor types: "render" prints the state.
var page = new PageModel();

// A synchronous handler: one render after it returns.
await page.HandleEventAsync("Add 1", () => { page.Count++; return Task.CompletedTask; });

// An async handler: render when it first waits, when it asks with StateHasChanged, and when it ends.
await page.HandleEventAsync("Save", async () =>
{
    page.Status = "Checking";
    await Task.Delay(20);
    page.Status = "Writing";
    page.StateHasChanged();
    await Task.Delay(20);
    page.Status = "Saved";
});

// A child invokes the parent's callback: the parent's method runs, then the parent renders.
var onRate = new CallbackModel<int>(page, stars => page.Rating = stars);
await onRate.InvokeAsync(4);

// A timer changes state outside any event: nothing renders until the code asks for it.
page.Seconds++;
page.Seconds++;
Console.WriteLine($"timer: Seconds is {page.Seconds}, the screen still shows: {page.Screen}");
Console.WriteLine("timer: StateHasChanged");
page.StateHasChanged();

sealed class PageModel
{
    public int Count;
    public string Status = "Idle";
    public int Rating;
    public int Seconds;
    private int renders;

    public string Screen { get; private set; } = "(nothing yet)";

    public void StateHasChanged()
    {
        renders++;
        Screen = $"count={Count} status={Status} rating={Rating} seconds={Seconds}";
        Console.WriteLine($"  render {renders}: {Screen}");
    }

    // After an event: run the handler, render, and if the handler is still running, render again when it ends.
    public async Task HandleEventAsync(string name, Func<Task> handler)
    {
        Console.WriteLine($"event: {name}");
        Task task = handler();
        StateHasChanged();
        if (!task.IsCompleted)
        {
            await task;
            StateHasChanged();
        }
    }
}

// Like EventCallback<T>: it remembers the component that created it (the receiver).
sealed class CallbackModel<T>(PageModel receiver, Action<T> method)
{
    public Task InvokeAsync(T value) =>
        receiver.HandleEventAsync($"callback({value})", () => { method(value); return Task.CompletedTask; });
}
Open C# practice

C# practice output

event: Add 1
  render 1: count=1 status=Idle rating=0 seconds=0
event: Save
  render 2: count=1 status=Checking rating=0 seconds=0
  render 3: count=1 status=Writing rating=0 seconds=0
  render 4: count=1 status=Saved rating=0 seconds=0
event: callback(4)
  render 5: count=1 status=Saved rating=4 seconds=0
timer: Seconds is 2, the screen still shows: count=1 status=Saved rating=4 seconds=0
timer: StateHasChanged
  render 6: count=1 status=Saved rating=4 seconds=2
Try this
Blazor renders after its own events and lifecycle methods. Code that runs outside them, such as a timer callback, must call InvokeAsync(StateHasChanged).

Further reading