Skip to content
Tutorials Center
My learning

Topics

Lesson 9 of 41 ยท Components and Razor Syntax

Component Lifecycle Methods

Learn the Blazor component lifecycle: SetParametersAsync, OnInitializedAsync, OnParametersSet, OnAfterRender, ShouldRender and IDisposable, with the right place to load data and clean up.

Every component goes through a series of steps: it is created, receives its parameters, renders, possibly renders many more times, and is finally removed. Blazor gives you lifecycle methods, which you override to run your code at each step. Choosing the right method is the difference between data that loads once, data that reloads when a parameter changes, and bugs where it loads over and over.

The order of events

flowchart TD
  A["Component created"] --> B["SetParametersAsync"]
  B --> C["OnInitialized / OnInitializedAsync (first time only)"]
  C --> D["OnParametersSet / OnParametersSetAsync"]
  D --> E["ShouldRender"]
  E --> F["BuildRenderTree"]
  F --> G["OnAfterRender / OnAfterRenderAsync"]
  G --> H["Event or parameter change: back to D"]
  H --> I["Dispose when removed"]

After the first render, later updates skip the initialization step and start again at "parameters set".

The methods

Method Runs Use it for
SetParametersAsync Every time the parent sets parameters Rarely overridden; advanced control
OnInitialized / OnInitializedAsync Once, when the component starts Loading initial data, setup
OnParametersSet / OnParametersSetAsync After each parameter assignment Reacting to a changed parameter
ShouldRender Before each render Skipping needless renders
OnAfterRender / OnAfterRenderAsync After each render, with firstRender Calling JavaScript, focusing elements
Dispose / DisposeAsync When removed Unsubscribing, stopping timers

Loading data in OnInitializedAsync

HTML
@page "/products"
@inject IProductService Products

@if (items is null)
{
    <p>Loading...</p>
}
else
{
    <ul>
        @foreach (var p in items)
        {
            <li>@p.Name</li>
        }
    </ul>
}

@code {
    private List<Product>? items;

    protected override async Task OnInitializedAsync()
    {
        items = await Products.GetAllAsync();
    }
}

The component renders before the await finishes (showing "Loading..."), and renders again when the method completes. Using null to mean "not loaded yet" is a standard pattern.

Reacting to changed parameters

OnInitialized runs once. If the component stays on screen and the parent changes a parameter (for example /product/1 navigates to /product/2 and reuses the same component), OnInitializedAsync will not run again. Use OnParametersSetAsync instead:

C#
[Parameter] public int Id { get; set; }

protected override async Task OnParametersSetAsync()
{
    product = await Products.GetAsync(Id);
}

This method also runs on the first load (after initialization), so one method often covers both needs. Compare with the previous value if the work is expensive.

OnAfterRender and JavaScript

OnAfterRender runs after the markup exists in the browser's DOM. That makes it the place to focus an input or start a chart library:

C#
protected override async Task OnAfterRenderAsync(bool firstRender)
{
    if (firstRender)
    {
        await JS.InvokeVoidAsync("focusElement", "search-box");
    }
}

Always check firstRender (or another guard) so you do not repeat the work on every render. Do not change state and call StateHasChanged unconditionally here, because that causes another render and an infinite loop. With server-side prerendering, OnAfterRender does not run during prerender because there is no browser yet. JS interop gets its own chapter.

Cleaning up with IDisposable

If a component subscribes to an event or starts a timer, it must stop when removed, or the old instance keeps running in memory:

HTML
@implements IDisposable

@code {
    private Timer? timer;

    protected override void OnInitialized()
    {
        timer = new Timer(_ => InvokeAsync(StateHasChanged), null, 1000, 1000);
    }

    public void Dispose() => timer?.Dispose();
}

For asynchronous cleanup implement IAsyncDisposable and DisposeAsync.

A runnable stand-in: watching the order

This stand-in has a base class that calls the same virtual methods in the same order as ComponentBase: first parameters, then initialization (once), then "parameters set", then render and "after render". Run it to see why OnInitialized fires only once.

C# Stand-in: lifecycle order

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Read the output top to bottom: OnInitializedAsync shows up in the first block only, while OnParametersSetAsync follows every parameter change, and the event handler triggers only render and after-render.

Which method for which job?

  • Load data once: OnInitializedAsync.
  • Load data that depends on a parameter: OnParametersSetAsync.
  • Talk to the DOM or JavaScript: OnAfterRenderAsync with a firstRender check.
  • Release resources: Dispose or DisposeAsync.
  • Avoid: heavy work in markup expressions and async void methods; return a Task instead.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which method runs only once, when the component first starts?

    Initialization happens once per component instance.
  2. 2. A route /product/{Id} reuses the same component when Id changes. Where should you reload the product?

    OnInitializedAsync will not run again; OnParametersSetAsync runs after each parameter change.
  3. 3. Why check firstRender in OnAfterRenderAsync?

    OnAfterRender runs after every render, so one-time work needs a guard.
  4. 4. Why implement IDisposable on a component that starts a timer?

    Without cleanup, the timer keeps running and holds the removed component in memory.

Summary

  • The lifecycle runs: set parameters, initialize (once), parameters set, render, after render.
  • Use OnInitializedAsync for first load, OnParametersSetAsync for parameter-dependent data.
  • Use OnAfterRenderAsync for DOM and JavaScript work, guarded by firstRender.
  • Implement IDisposable or IAsyncDisposable to unsubscribe and stop timers.

Next: Conditionals and Loops