SharpRuneOpen playground

The component lifecycle

Follow SetParametersAsync, OnInitialized, OnParametersSet, OnAfterRender, ShouldRender and disposal in a page that is reused between routes.

  • 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

The lifecycle of Item across two routes

  1. SetParametersAsync: Id 0 to 1the Router passes route values to a new instance #1
  2. OnInitialized, then OnInitializedAsynconce per instance; OnInitialized starts the timer and subscribes
  3. Render #1, then OnAfterRender(true)the unfinished async task lets Blazor render at once
  4. OnParametersSet, then OnParametersSetAsyncrenders #2 and #3; the details for item 1 arrive
  5. items/2 reuses instance #1only SetParametersAsync and the OnParametersSet pair run again
  6. Navigating to / disposes the pagethe timer stops; 0 subscribers are left

Read it as the companion's log, top to bottom: setup runs once per instance, parameter work runs on every change. Load data for a route value in OnParametersSet, not OnInitialized.

SetParametersAsync starts every cycle

A component is a class, and the renderer talks to it through the IComponent interface, which has two methods: Attach and SetParametersAsync. Every time the parent renders and passes parameters, the renderer calls SetParametersAsync with a ParameterView, a read-only set of names and values. For a page, the parent is RouteView and the values come from the route. ComponentBase implements SetParametersAsync by copying the values into the matching [Parameter] properties and then running the lifecycle methods you override. Overriding SetParametersAsync yourself is rare. LifecycleLab does it to log the old and the new Id: before the call to the base method, Id still holds the previous value.

The first call on a new instance runs OnInitialized and then OnInitializedAsync. Every call, the first one included, then runs OnParametersSet and OnParametersSetAsync. Each synchronous method runs before its async partner. After the parameter methods the component renders. That is the whole difference between the two pairs: initialization runs once per instance, and parameter handling runs every time parameters arrive.

When the same page is reused

Navigation does not always create a new component. RouteView renders the page type for the new address, and if that type is the same as before, the renderer keeps the instance and calls SetParametersAsync with the new values. Going from items/1 to items/2 is that case: Item stays instance #1, its timer keeps counting, and only SetParametersAsync and OnParametersSet run. Code that loads data for Id in OnInitialized would keep showing item 1. Put work that depends on parameters in OnParametersSet or OnParametersSetAsync, and keep OnInitialized for setup that belongs to the instance, such as creating a timer or subscribing to a service event.

Async methods and intermediate renders

When OnInitializedAsync or OnParametersSetAsync returns a task that has not finished, ComponentBase does not wait silently. It renders the component at once, so the page can show a placeholder, then awaits the task and renders again. Item.razor uses this: OnParametersSetAsync sets details to null and awaits a short delay, so Fetching details… appears first and the real text follows. Every field that an async method fills must be safe to render while it is still null.

This also explains an order in the LifecycleLab log that surprises many developers. OnInitializedAsync waits 200 milliseconds, so the first render happens during that wait, and OnAfterRender: firstRender = true is logged before OnInitializedAsync: finished and before OnParametersSet. If all lifecycle methods finished synchronously, the first render would come after OnParametersSet.

OnAfterRender and ShouldRender

OnAfterRender and OnAfterRenderAsync run after a render has been applied to the browser's DOM. This is the place for JavaScript interop that needs elements, for example focusing an input or starting a chart library. firstRender is true only for the first render of an instance, so one-time DOM work goes inside if (firstRender). Blazor does not render again when the task from OnAfterRenderAsync completes. If you change state there and need it on screen, call StateHasChanged, and guard that call, or the component renders in an endless loop.

ShouldRender lets a component refuse a render. ComponentBase asks it each time StateHasChanged is called, including the automatic call after an event handler, but not before the very first render. Item.razor returns !paused. While the box is checked, clicks and timer ticks change fields but the screen stays as it was. Clearing the box is an event too: the handler sets paused to false, ShouldRender returns true, and the latest values appear together. ShouldRender is a performance tool for components with expensive markup, not a way to hide bugs.

Disposal, timers and subscriptions

When a component leaves the render tree, Blazor checks whether it implements IDisposable or IAsyncDisposable and calls Dispose or DisposeAsync. If a component implements both, only DisposeAsync runs. In a .razor file you declare the interface with @implements. Anything outside the component that holds a reference to it must be released here: a System.Threading.Timer, a handler attached with += to a service event or to NavigationManager.LocationChanged, a CancellationTokenSource for pending work. Without that step the timer keeps firing and the event source keeps the component alive after it has left the screen.

Timer callbacks need one more step. The timer calls your method on its own schedule, outside the renderer's normal flow. InvokeAsync runs a piece of work on the renderer's dispatcher, and state changes followed by StateHasChanged belong inside it. In today's single-threaded WebAssembly runtime a direct StateHasChanged call from a timer often works anyway, but on the server and in multithreaded hosting it throws, because the callback runs on a thread the renderer does not own. Use InvokeAsync from the start, as Item.razor and the quiz example do.

Trace LifecycleLab

Tap Item 1 on Home. The Router creates Item, the container injects LifecycleLog, and SetParametersAsync logs Id 0 -> 1. OnInitialized takes instance number 1 and starts a timer with a one-second period. OnInitializedAsync begins its delay, so the first render happens and OnAfterRender logs firstRender = true. When the delay ends, OnParametersSet logs Id = 1 and OnParametersSetAsync fetches the details. Each tick increases seconds inside InvokeAsync and renders again, which also shows log entries added since the previous render.

Tap Next. SetParametersAsync logs Id 1 -> 2 and OnParametersSet logs Id = 2. Nothing else runs, the instance number stays 1 and the seconds continue. Tap Home. RouteView now renders Home instead of Item, so the renderer disposes Item: DisposeAsync awaits the timer's own DisposeAsync and logs that the timer stopped. Home reads the same singleton log and shows that last line. Opening an item again creates instance #2.

Mistakes, practice and review

Typical mistakes are loading data for a route parameter in OnInitialized, rendering a field filled by OnInitializedAsync without a null check, calling StateHasChanged in OnAfterRender without a guard, creating a timer or subscription without disposing it, and calling StateHasChanged from a timer without InvokeAsync.

To practice, give OnParametersSetAsync a CancellationTokenSource: pass its token to Task.Delay, cancel the previous source when Id changes and cancel it in DisposeAsync. Tap Next twice quickly and check that the details always match the Id in the heading. Then move the detail fetch into OnInitializedAsync and describe what breaks when you tap Next. Finally, change the console companion so that ShouldRender returns false on every second tick, and predict its log before you run it.

Key points
  • SetParametersAsync assigns parameters. OnInitialized(Async) runs once per instance; OnParametersSet(Async) runs on every parameter change.
  • An async lifecycle method that has not finished causes a render before it completes and another one after.
  • OnAfterRender(firstRender) runs after the DOM update, and Blazor does not render again after OnAfterRenderAsync.
  • ShouldRender is skipped for the first render and can block later ones.
  • Implement IDisposable or IAsyncDisposable to stop timers and remove event handlers, and update state from timers through InvokeAsync.
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.

The component lifecycle — 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. Open Item 1 and read the log. Tap Next, then Previous, and watch which lines are added and whether the instance number and seconds change.
  3. Check Pause rendering and tap Click a few times, then clear the box. Finally tap Home and read the last line of the log.
  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

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

  <PropertyGroup>
    <TargetFramework>net9.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <AssemblyName>LifecycleLab</AssemblyName>
    <RootNamespace>LifecycleLab</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 LifecycleLab;
using LifecycleLab.Services;

var builder = WebAssemblyHostBuilder.CreateDefault(args);
builder.RootComponents.Add<App>("#app");
builder.RootComponents.Add<HeadOutlet>("head::after");

// One log for the whole app, so entries survive after a page is disposed.
builder.Services.AddSingleton<LifecycleLog>();

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>
        <main>
            <h1>Not found</h1>
            <p>There is no page at this address. <a href="">Go to the start page</a>.</p>
        </main>
    </NotFound>
</Router>
_Imports.razorDownload file ↗
_Imports.razor
@using System.Net.Http
@using System.Net.Http.Json
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using Microsoft.JSInterop
@using LifecycleLab
@using LifecycleLab.Services
Pages/Home.razorDownload file ↗
Pages/Home.razor
@page "/"
@inject LifecycleLog Log

<PageTitle>Lifecycle Lab</PageTitle>

<main>
    <h1>Lifecycle Lab</h1>

    <p>Open an item. Move to the next item, then come back here. Item.razor writes every lifecycle method it runs into a shared log.</p>

    <ul class="cards">
        <li><a href="items/1"><strong>Item 1</strong><span>items/1</span></a></li>
        <li><a href="items/2"><strong>Item 2</strong><span>items/2</span></a></li>
        <li><a href="items/3"><strong>Item 3</strong><span>items/3</span></a></li>
    </ul>

    <h2>Log</h2>
    @if (Log.Entries.Count == 0)
    {
        <p class="muted">Empty. Open an item to fill it.</p>
    }
    else
    {
        <ol class="log">
            @foreach (var entry in Log.Entries)
            {
                <li>@entry</li>
            }
        </ol>
        <button @onclick="Log.Clear">Clear the log</button>
    }
</main>
Pages/Item.razorDownload file ↗
Pages/Item.razor
@page "/items/{Id:int}"
@implements IAsyncDisposable
@inject LifecycleLog Log

<PageTitle>Item @Id</PageTitle>

<main>
    <h1>Item @Id</h1>
    <p class="details">@(details ?? "Fetching details…")</p>

    <div class="row">
        @if (Id > 1)
        {
            <a class="chip" href="items/@(Id - 1)">Previous</a>
        }
        <a class="chip" href="items/@(Id + 1)">Next</a>
        <a class="chip" href="">Home</a>
    </div>

    <div class="panel">
        <p>Component instance <strong>#@instance</strong>, alive for <strong>@seconds s</strong>.</p>
        <p class="muted">Previous and Next keep this instance, so the seconds keep counting. Home disposes it.</p>
    </div>

    <div class="panel">
        <label class="check"><input type="checkbox" @bind="paused" /> Pause rendering</label>
        <div class="row">
            <button class="primary" @onclick="() => clicks++">Click</button>
            <span>Clicks: <strong>@clicks</strong></span>
        </div>
        <p class="muted">While paused, ShouldRender returns false. Clicks and seconds still count, but the screen does not change until you clear the box.</p>
    </div>

    <h2>Lifecycle log</h2>
    <ol class="log">
        @foreach (var entry in Log.Entries)
        {
            <li>@entry</li>
        }
    </ol>
</main>

@code {
    // Filled from the {Id:int} segment of the address.
    [Parameter]
    public int Id { get; set; }

    private int instance;
    private int seconds;
    private int clicks;
    private bool paused;
    private string? details;
    private Timer? timer;

    // Runs first, every time the Router passes parameters. Id still has its old value here.
    public override async Task SetParametersAsync(ParameterView parameters)
    {
        var next = parameters.GetValueOrDefault<int>(nameof(Id));
        Log.Add($"SetParametersAsync: Id {Id} -> {next}");
        await base.SetParametersAsync(parameters); // assigns Id, then runs the methods below
    }

    // Runs once per component instance.
    protected override void OnInitialized()
    {
        instance = Log.NextInstance();
        timer = new Timer(OnTimer, null, 1000, 1000);
        Log.Add($"OnInitialized: instance #{instance}, timer started");
    }

    // Also once. The first render happens while this method awaits.
    protected override async Task OnInitializedAsync()
    {
        await Task.Delay(200);
        Log.Add("OnInitializedAsync: finished");
    }

    // Runs after initialization and again every time Id changes.
    protected override void OnParametersSet()
    {
        paused = false;
        Log.Add($"OnParametersSet: Id = {Id}");
    }

    protected override async Task OnParametersSetAsync()
    {
        details = null;
        await Task.Delay(500); // stands in for an HTTP call that depends on Id
        details = $"Details for item {Id}, fetched in OnParametersSetAsync.";
    }

    // Runs after the browser's page has been updated. firstRender is true once per instance.
    protected override void OnAfterRender(bool firstRender)
    {
        if (firstRender) Log.Add("OnAfterRender: firstRender = true");
    }

    // Asked before every render except the first one.
    protected override bool ShouldRender() => !paused;

    // The timer calls this on its own schedule, outside Blazor's rendering.
    // InvokeAsync runs the update on the renderer, where StateHasChanged belongs.
    private void OnTimer(object? state) => _ = InvokeAsync(() =>
    {
        seconds++;
        StateHasChanged();
    });

    // Blazor calls this when the component leaves the page. Without it, the timer would keep firing.
    public async ValueTask DisposeAsync()
    {
        if (timer is not null) await timer.DisposeAsync();
        Log.Add($"DisposeAsync: instance #{instance}, timer stopped");
    }
}
Services/LifecycleLog.csDownload file ↗
Services/LifecycleLog.cs
namespace LifecycleLab.Services;

// Collects the lifecycle messages that Item.razor writes.
public sealed class LifecycleLog
{
    private readonly List<string> entries = [];
    private int instances;

    public IReadOnlyList<string> Entries => entries;

    // Gives each new Item component its own number.
    public int NextInstance() => ++instances;

    public void Add(string message)
    {
        entries.Add(message);
        if (entries.Count > 30) entries.RemoveAt(0);
    }

    public void Clear() => entries.Clear();
}
wwwroot/css/app.cssDownload file ↗
wwwroot/css/app.css
:root {
    color-scheme: light dark;
    --accent: #6b4eff;
    --line: #d8d6e4;
}

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

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

a {
    color: var(--accent);
}

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

h1:focus {
    outline: none;
}

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

code {
    font-size: 0.9em;
    overflow-wrap: anywhere;
}

.loading {
    padding: 32px 16px;
    color: #777;
}

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

input:not([type=checkbox]) {
    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;
}

.muted {
    color: #777;
}

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

main {
    padding: 20px 16px 40px;
    max-width: 720px;
    margin: 0 auto;
}

.cards {
    list-style: none;
    padding: 0;
    display: grid;
    gap: 10px;
}

.cards a {
    display: flex;
    flex-direction: column;
    padding: 12px 16px;
    border: 1px solid var(--line);
    border-radius: 12px;
    color: inherit;
    text-decoration: none;
}

.cards span {
    color: #777;
}

.chip {
    display: inline-block;
    padding: 6px 12px;
    border: 1px solid var(--line);
    border-radius: 999px;
    text-decoration: none;
}

.details {
    min-height: 1.5em;
}

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

.panel p {
    margin: 4px 0;
}

.check {
    display: flex;
    align-items: center;
    gap: 8px;
}

.check input {
    width: 20px;
    height: 20px;
}

.log {
    padding-left: 24px;
    font-family: ui-monospace, Menlo, monospace;
    font-size: 0.82rem;
}

.log li {
    margin: 3px 0;
    overflow-wrap: anywhere;
}
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>Lifecycle Lab</title>
    <base href="/" />
    <link rel="stylesheet" href="css/app.css" />
    <link rel="stylesheet" href="LifecycleLab.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>

Expected result

Item 1 shows Fetching details… for less than a second, then Details for item 1. The log lists SetParametersAsync: Id 0 -> 1, OnInitialized: instance #1, timer started, OnAfterRender: firstRender = true, OnInitializedAsync: finished and OnParametersSet: Id = 1, in that order. The seconds counter rises once per second. Next adds only SetParametersAsync: Id 1 -> 2 and OnParametersSet: Id = 2; the instance stays #1 and the seconds keep counting. While Pause rendering is checked, the Clicks value and the seconds stop changing on screen; clearing the box shows the real click count at once. Home shows the log ending with DisposeAsync: instance #1, timer stopped, and opening another item starts instance #2.

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.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

// A hand-written model of the order in which ComponentBase calls its lifecycle methods.
// It uses no Blazor types; it only replays the rules with a log.
var log = new List<string>();
var ticker = new Ticker();
var router = new Router(log, ticker);

await router.Navigate("/items/1");
await router.Navigate("/items/2");
router.Current!.Paused = true;
ticker.Tick();
router.Current!.Paused = false;
ticker.Tick();
await router.Navigate("/");
ticker.Tick();

for (var i = 0; i < log.Count; i++)
{
    Console.WriteLine($"{i + 1:D2}. {log[i]}");
}

// An event source, like a timer or a service that raises Changed.
sealed class Ticker
{
    public event Action? Ticked;

    public int Subscribers => Ticked?.GetInvocationList().Length ?? 0;

    public void Tick() => Ticked?.Invoke();
}

// Reuses the page component when the same template matches, as Blazor's Router does.
sealed class Router(List<string> log, Ticker ticker)
{
    private ItemPage? current;
    private int instances;

    public ItemPage? Current => current;

    public async Task Navigate(string path)
    {
        log.Add($"-- navigate to {path}");
        if (path.StartsWith("/items/"))
        {
            current ??= new ItemPage(log, ticker, ++instances);
            await current.SetParametersAsync(int.Parse(path["/items/".Length..]));
        }
        else if (current is not null)
        {
            current.Dispose();
            current = null;
            log.Add($"subscribers left on the ticker: {ticker.Subscribers}");
        }
    }
}

sealed class ItemPage(List<string> log, Ticker ticker, int instance) : IDisposable
{
    private bool initialized;
    private bool rendered;
    private int renders;

    public int Id { get; private set; }

    public bool Paused { get; set; }

    // Mirrors ComponentBase.SetParametersAsync: assign, initialize once, then parameters-set, rendering in between.
    public async Task SetParametersAsync(int id)
    {
        log.Add($"SetParametersAsync: Id {Id} -> {id}");
        Id = id;
        if (!initialized)
        {
            initialized = true;
            OnInitialized();
            var init = OnInitializedAsync();
            if (!init.IsCompleted)
            {
                Render(); // the first render does not wait for OnInitializedAsync
                await init;
            }
        }

        OnParametersSet();
        var set = OnParametersSetAsync();
        Render();
        if (!set.IsCompleted)
        {
            await set;
            Render();
        }
    }

    private void OnInitialized()
    {
        ticker.Ticked += OnTick;
        log.Add($"OnInitialized: instance #{instance}, subscribed");
    }

    private async Task OnInitializedAsync()
    {
        await Task.Delay(10);
        log.Add("OnInitializedAsync: finished");
    }

    private void OnParametersSet() => log.Add($"OnParametersSet: Id = {Id}");

    private async Task OnParametersSetAsync()
    {
        await Task.Delay(10);
        log.Add($"OnParametersSetAsync: details for {Id} fetched");
    }

    private void OnTick()
    {
        log.Add($"tick reached instance #{instance}");
        Render();
    }

    // ShouldRender is not asked before the first render.
    private void Render()
    {
        if (rendered && !ShouldRender())
        {
            log.Add("ShouldRender: false, render skipped");
            return;
        }

        renders++;
        var first = !rendered;
        rendered = true;
        log.Add($"render #{renders} of Item {Id}");
        OnAfterRender(first);
    }

    private bool ShouldRender() => !Paused;

    private void OnAfterRender(bool firstRender)
    {
        if (firstRender) log.Add("OnAfterRender: firstRender = True");
    }

    // Without the unsubscribe, the ticker would keep this page alive and keep calling it.
    public void Dispose()
    {
        ticker.Ticked -= OnTick;
        log.Add($"Dispose: instance #{instance}, unsubscribed");
    }
}
Open C# practice

C# practice output

01. -- navigate to /items/1
02. SetParametersAsync: Id 0 -> 1
03. OnInitialized: instance #1, subscribed
04. render #1 of Item 1
05. OnAfterRender: firstRender = True
06. OnInitializedAsync: finished
07. OnParametersSet: Id = 1
08. render #2 of Item 1
09. OnParametersSetAsync: details for 1 fetched
10. render #3 of Item 1
11. -- navigate to /items/2
12. SetParametersAsync: Id 1 -> 2
13. OnParametersSet: Id = 2
14. render #4 of Item 2
15. OnParametersSetAsync: details for 2 fetched
16. render #5 of Item 2
17. tick reached instance #1
18. ShouldRender: false, render skipped
19. tick reached instance #1
20. render #6 of Item 2
21. -- navigate to /
22. Dispose: instance #1, unsubscribed
23. subscribers left on the ticker: 0
Try this
Code that depends on a route parameter belongs in OnParametersSet or OnParametersSetAsync, not OnInitialized, because moving between items/1 and items/2 reuses the component.

Further reading