Component Lifecycle in Blazor

By Syncfusion®, Inc. · Last updated

The order of Blazor's lifecycle methods: OnInitialized(Async), SetParametersAsync, OnParametersSet(Async), route parameter changes, re-render triggers, StateHasChanged, ShouldRender, @key, OnAfterRender with firstRender, and Dispose.

What you will learn

  • Name the lifecycle methods in order
  • Load data in OnInitializedAsync and react to parameters in OnParametersSet
  • Update the page with StateHasChanged and keep list items with @key
  • Run one-time setup with firstRender and clean up in Dispose

Lifecycle Overview

  • The component lifecycle is the set of steps a component goes through: it is created, updated and removed.
  • At each step, Blazor calls a lifecycle method, for example OnInitialized.
  • You use them by writing protected override and the method name in @code.
  • Using lifecycle methods lets you load data, update values and clean up at the right time.

Real-World Example:

  • Ravi's order page loads the menu when it opens.
  • It updates the bill when the cups change.
  • It stops a timer when the customer leaves.
  • Each job uses a different lifecycle method.

Simple lesson: Lifecycle methods let you run code at the right moment in a component's life.

Lifecycle Order

Blazor calls the methods in this order:

  1. SetParametersAsync: the parameters arrive.
  2. OnInitialized / OnInitializedAsync: first time only.
  3. OnParametersSet / OnParametersSetAsync: every time the parameters are set.
  4. Render: Blazor works out the HTML.
  5. OnAfterRender / OnAfterRenderAsync: the HTML is now in the browser.
  6. Dispose: the component is removed (only if you implement it).

Animation: a dot moves through the lifecycle steps in order: SetParametersAsync, OnInitialized (first time only), OnParametersSet, Render, OnAfterRender. A loop arrow goes from OnAfterRender back to OnParametersSet for later updates. Dispose sits at the end.

SetParameters Async

OnInitialized first time only

OnParametersSet

Render

OnAfterRender

parent sends new parameters: run again (no OnInitialized)

Dispose (removed)

The lifecycle in order. Later updates skip OnInitialized and start again at OnParametersSet.

Press ▶ Run and read the Console. Each method prints its name, so you can see the order. Then click the button.

The box opens on Bill.razor, which has the lifecycle methods. Order.razor is its parent.

  • On the first run you see 1, 2 and 3. After a click you see only 2 and 3. OnInitialized does not run again.

Simple lesson: Initialize once, then parameters, render and after-render, again and again. Dispose at the end.

Initialization

OnInitialized

  • Runs once, when the component is first created.
  • Parameters are already set, so you can use them here.
  • Use it to set starting values.

OnInitializedAsync

  • The async version. Use it when you must wait for something, like loading data from a web API.
  • Blazor renders the page before the wait ends, and again after it. So show a "Loading..." message while the data is null.

Always handle null while async data loads. If you write @foreach (var tea in menu) without the @if, the first render fails, because menu is still null.

Simple lesson: Use OnInitialized for starting values, and OnInitializedAsync to load data. Show "Loading..." until it arrives.

Parameter Updates

SetParametersAsync

  • The very first step. It receives all incoming parameters and copies them into your properties.
  • You rarely override it. If you do, call await base.SetParametersAsync(parameters). Otherwise your properties stay empty.

In the below example, TeaCup.razor overrides SetParametersAsync. It saves the old Size, calls base.SetParametersAsync to copy in the new value, and then shows both.

  • Click Large. A new line shows the old and the new size. Without the base.SetParametersAsync line, Size is never set and the cup does not update.

OnParametersSet

  • Runs after the parameters are set: on the first render and every time the parent sends new values.
  • Use it to work out values that depend on parameters, like a total.

OnParametersSetAsync

  • The async version, for example to load data for a new parameter value.

Route Parameter Changes

  • When a user goes from /tea/masala to /tea/ginger, Blazor reuses the same page component. It does not create a new one.
  • So OnInitialized does not run again. Only OnParametersSet runs.
  • Load data that depends on a route parameter in OnParametersSet(Async), not in OnInitialized.

Animation: the parent Home sends Name = masala, then Name = ginger, to TeaDetails. Each time a value arrives, OnParametersSet runs and the price updates from 20 to 25.

Home (parent) sends Name

Name = "masala" Name = "ginger"

TeaDetails

OnParametersSet() runs Price: ₹20 Price: ₹25

Every new parameter value runs OnParametersSet again, so the price stays correct.

This is a common bug: the address changes to /tea/ginger, but the page still shows Masala data. The fix is to move the loading code from OnInitialized to OnParametersSet.

In the box below, Home changes the Name parameter, like a user moving between tea pages.

The box opens on TeaDetails.razor. Compare the code in OnInitialized and OnParametersSet.

  • Click Ginger. The OnParametersSet price changes to ₹25. The OnInitialized price stays at ₹20, because it ran only once.

Simple lesson: Values that depend on parameters belong in OnParametersSet, because it runs on every change.

Rendering

Re-rendering Triggers

Blazor renders a component again automatically when:

  • An event handler in it finishes, like @onclick.
  • Its parent renders and passes it parameters.
  • An EventCallback it raised finishes (the parent renders).
  • You call StateHasChanged().

Animation: four triggers send a dot, one after another, into the Render step: an event handler like @onclick finishing, the parent passing parameters, an EventCallback finishing, and a call to StateHasChanged. After Render, the page updates.

@onclick finishes

parent passes parameters

EventCallback finishes

StateHasChanged()

Render

page updated

Any of these four things makes Blazor render the component again.

Manual Updates (StateHasChanged)

  • Some changes happen outside a Blazor event, for example a timer.
  • Blazor does not know about them, so the page does not update.
  • Call StateHasChanged() to say "my data changed, please render again".
  • From a timer, use InvokeAsync(StateHasChanged).
  • Delete the line with InvokeAsync(StateHasChanged) and press ▶ Run. The number stays at 0, even though seconds keeps growing.

Render Control (ShouldRender)

  • ShouldRender() returns true or false. If it returns false, Blazor skips the update.
  • Use it rarely, only to skip costly renders. The first render always happens.
  • Click Pause screen, then New order a few times. The number does not change. Click Resume, and the real count appears.
  • Notice the pause button's own text also stays the same while paused. Nothing in this component renders.

Element Keys (@key)

  • When a list changes, Blazor matches old and new items by position.
  • If you add an item at the top, every row is matched with the wrong item. Text typed in a box can jump to the wrong row.
  • @key gives each row a fixed ID, so Blazor matches items by key instead.

Animation: a new tea, Lemon, is added at the top of a list. Without @key, the note typed next to Masala moves to Lemon's row. With @key, the note stays with Masala. Without @key With @key

Masala

Lemon (new)

"no sugar"

Masala ✗ the note moved to Lemon

Lemon (new)

Masala

"no sugar"

✓ the note stays with Masala

@key tells Blazor which row is which, so the right data stays with the right item.

  • Type a note next to Masala Tea in both lists, then click the button. Without @key, your note jumps to Lemon Tea. With @key, it stays with Masala Tea.

Simple lesson: Blazor re-renders after events and parameter changes. Call StateHasChanged for other changes. Use @key in lists that change.

After Render

OnAfterRender

  • Runs after the HTML is in the browser.
  • Use it for work that needs the real page, like calling a JavaScript library to draw a chart.

OnAfterRenderAsync

  • The async version, for example to call JavaScript and wait for it.

First Render (firstRender)

  • Both methods get bool firstRender. It is true only the first time.
  • Put one-time setup inside if (firstRender) { ... }. Otherwise it runs after every render.
  • If you change data here, call StateHasChanged(). Blazor does not render again on its own after this method.
  • Renders so far is always one behind. It changes after the HTML is drawn, so the next render shows it.

Never call StateHasChanged() in OnAfterRender without if (firstRender). Each render would start a new render, forever.

Simple lesson: OnAfterRender runs after the HTML is in the browser. Do one-time setup only when firstRender is true.

Disposal

  • Disposal means cleaning up or releasing resources when a component is no longer needed.
  • It helps stop running tasks, remove event subscriptions, and free resources to avoid unnecessary memory usage.

Animation: a TeaTimer component is on the page with its timer ticking. The user goes to another page. Blazor calls Dispose, the timer stops, and the component is removed.

TeaTimer ⏱ timer: ticking ⏹ timer: stopped on the page

user goes to /menu

Dispose()

timer stopped memory freed

When the component leaves the page, Blazor calls Dispose so the timer stops.

@implements

  • @implements tells the component to follow a specific interface, such as IDisposable.
  • It is the Razor equivalent of writing : IDisposable in a C# class.

IDisposable

  • Use IDisposable when the component starts something that needs to be stopped later, such as a timer or event subscription.
  • Add @implements IDisposable and create a Dispose() method.
  • Blazor automatically calls Dispose() when the component is removed from the page, such as when navigating to another page.

In the below example, TeaTimer.razor starts a timer, and its Dispose() method stops the timer when the component is removed.

  • Click Close the tea timer. The @if removes TeaTimer, so Blazor calls Dispose. The Console shows "Dispose: timer stopped".

IAsyncDisposable

  • Use IAsyncDisposable when cleanup requires an asynchronous operation, such as releasing a JavaScript object.
  • Add @implements IAsyncDisposable and create a DisposeAsync() method.

Simple lesson: Stop timers and subscriptions in Dispose. Add @implements IDisposable to get it called.

Common mistakes

MistakeWrong ideaCorrect ideaWhat goes wrong
Loading route data in OnInitializedIt runs on every page changeUse OnParametersSet(Async)The page keeps the old data
@foreach over data that is still loadingThe data is there at the first renderCheck for null first and show "Loading..."An error on the first render
Changing data in a timer without StateHasChangedBlazor sees every changeCall InvokeAsync(StateHasChanged)The page does not update
StateHasChanged() in OnAfterRender without firstRenderIt runs onceWrap it in if (firstRender)Renders forever
A list that changes, without @keyBlazor matches items by valueAdd @key to each itemTyped text jumps to another row
A timer without DisposeIt stops when the page closes@implements IDisposable and stop itThe timer keeps running

Check Yourself

Exercises

What to Remember

  • Order: SetParametersAsync → OnInitialized(Async) (once) → OnParametersSet(Async) → render → OnAfterRender(Async) → Dispose.
  • Load data in OnInitializedAsync. Handle null while it loads.
  • Work that depends on parameters, including route parameters, goes in OnParametersSet(Async).
  • Call StateHasChanged() for changes outside Blazor events, like timers. ShouldRender can skip renders.
  • Use @key in lists that change.
  • Use if (firstRender) in OnAfterRender.
  • Stop timers in Dispose with @implements IDisposable.

Next: Layouts