State, forms and lifecycle
State, forms and lifecycle
A component can be created, receive parameters, render repeatedly and eventually be disposed. Lifecycle callbacks describe these transitions; form validation is a separate layer that helps users correct input before a mutation.
OnInitialized initializes instance-owned state; OnParametersSet responds to parameters, which can arrive more than once. With prerendering a component may be initialized in separate instances, so initialization must not trigger duplicate durable writes. OnAfterRender and its async counterpart run after interactive rendering, not prerendering. Use firstRender for one-time DOM initialization and guard async state changes after disposal. A component can be reentered while awaiting an incomplete task: keep its state renderable before each await, and reject stale results when parameters change. Completion of OnAfterRenderAsync does not automatically schedule another render; if its work changes visible state, request a guarded update without creating a render loop. For timers or external notifications, marshal changes through InvokeAsync, unsubscribe and cancel owned work during disposal. EditForm manages an EditContext, DataAnnotationsValidator connects annotation checks, and OnValidSubmit runs for a valid submission. On the server validate and authorize again before persistence; do not rely on the client to enforce rules. The examples have no external service or persistent data; wait for interactivity before use.
Baseline: .NET 10 / C# 14. In an approved environment use the complete fixture project, restore only reviewed dependencies from approved sources, then run dotnet build --no-restore and dotnet run --no-build --no-launch-profile. Blazor projects use localhost:5087; stop the server with Ctrl+C. Other examples start a bounded local server and client in one process. No real credentials or external services. Expected results are reasoned, not executed.
Derive display state from a parameter
Change the parent value and observe the child.
using Fixture;var builder = WebApplication.CreateBuilder(args);builder.WebHost.ConfigureKestrel(o => o.ListenLocalhost(5087));builder.Services.AddRazorComponents().AddInteractiveServerComponents();var app = builder.Build();app.UseAntiforgery();app.MapStaticAssets();app.MapRazorComponents<App>().AddInteractiveServerRenderMode();app.Run();App.razor
@using Microsoft.AspNetCore.Components.Routing<!DOCTYPE html><html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><base href="/" /><title>ByteMind local lab</title></head><body><main><Router AppAssembly="typeof(App).Assembly"><Found Context="route"><RouteView RouteData="route" /></Found></Router></main><script src="_framework/blazor.web.js"></script></body></html>Demo.razor
@page "/"@using Microsoft.AspNetCore.Components@using Microsoft.AspNetCore.Components.Web@using Microsoft.AspNetCore.Components.Forms@using static Microsoft.AspNetCore.Components.Web.RenderMode@rendermode InteractiveServer<h1>Pack size</h1><button type="button" @onclick="() => count++">Increase</button><PackSummary Count="count" />@code { private int count = 2; }PackSummary.razor
@using Microsoft.AspNetCore.Components<p role="status">Units: @units</p>@code { [Parameter] public int Count { get; set; } private int units; protected override void OnParametersSet() => units = Count * 2;}Expected result (not executed):
Units: 4 initially; Units: 6 after one click.The child derives its displayed total when parameters are assigned.
Validate a simple form
Submit blank, then type Atlas and submit again.
using Fixture;var builder = WebApplication.CreateBuilder(args);builder.WebHost.ConfigureKestrel(o => o.ListenLocalhost(5087));builder.Services.AddRazorComponents().AddInteractiveServerComponents();var app = builder.Build();app.UseAntiforgery();app.MapStaticAssets();app.MapRazorComponents<App>().AddInteractiveServerRenderMode();app.Run();App.razor
@using Microsoft.AspNetCore.Components.Routing<!DOCTYPE html><html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><base href="/" /><title>ByteMind local lab</title></head><body><main><Router AppAssembly="typeof(App).Assembly"><Found Context="route"><RouteView RouteData="route" /></Found></Router></main><script src="_framework/blazor.web.js"></script></body></html>Demo.razor
@page "/"@using Microsoft.AspNetCore.Components@using Microsoft.AspNetCore.Components.Web@using Microsoft.AspNetCore.Components.Forms@using static Microsoft.AspNetCore.Components.Web.RenderMode@rendermode InteractiveServer@using System.ComponentModel.DataAnnotations<h1>Reserve a title</h1><EditForm Model="model" OnValidSubmit="Accept" FormName="reservation"> <DataAnnotationsValidator /> <label for="title">Title</label> <InputText id="title" @bind-Value="model.Title" /> <ValidationMessage For="() => model.Title" /> <button type="submit">Reserve</button></EditForm><p role="status">@message</p>@code { private Request model = new(); private string message = "Not submitted"; private void Accept() => message = $"Preview accepted: {model.Title}"; private sealed class Request { [Required(ErrorMessage="Enter a title.")] public string Title { get; set; } = ""; }}Expected result (not executed):
Blank submit: Enter a title. / Not submitted. Valid submit: Preview accepted: Atlas.The valid-submit callback changes only local preview state; a real reservation needs independent checks.
Detect the first interactive render
Observe the state after the browser becomes interactive.
using Fixture;var builder = WebApplication.CreateBuilder(args);builder.WebHost.ConfigureKestrel(o => o.ListenLocalhost(5087));builder.Services.AddRazorComponents().AddInteractiveServerComponents();var app = builder.Build();app.UseAntiforgery();app.MapStaticAssets();app.MapRazorComponents<App>().AddInteractiveServerRenderMode();app.Run();App.razor
@using Microsoft.AspNetCore.Components.Routing<!DOCTYPE html><html lang="en"><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1" /><base href="/" /><title>ByteMind local lab</title></head><body><main><Router AppAssembly="typeof(App).Assembly"><Found Context="route"><RouteView RouteData="route" /></Found></Router></main><script src="_framework/blazor.web.js"></script></body></html>Demo.razor
@page "/"@using Microsoft.AspNetCore.Components@using Microsoft.AspNetCore.Components.Web@using Microsoft.AspNetCore.Components.Forms@using static Microsoft.AspNetCore.Components.Web.RenderMode@rendermode InteractiveServer<h1>Lifecycle indicator</h1><p role="status">@message</p>@code { private string message = "Initial markup"; protected override void OnAfterRender(bool firstRender) { if (firstRender) { message = "Interactive render completed"; StateHasChanged(); } }}Expected result (not executed):
Eventually: Interactive render completed. Initial markup may appear briefly.A first-render guard prevents repeatedly requesting new renders.
Apply the concept
Design a component that subscribes to an inventory notification source and is removed during navigation. Describe initialization, UI update and disposal steps, including prerendering.
Use the manual practice and knowledge check to reason about the boundary. Do not deploy these local demonstrations as production services.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
State, forms and lifecycle — knowledge check
Apply the lesson concepts to the following scenarios.
Which callback is appropriate for recomputing derived state from changed parameters?
Is OnAfterRender called during prerendering?
What does OnValidSubmit indicate?
Why guard StateHasChanged inside OnAfterRender?
What should disposal do for owned external subscriptions?