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 overrideand 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:
SetParametersAsync: the parameters arrive.OnInitialized/OnInitializedAsync: first time only.OnParametersSet/OnParametersSetAsync: every time the parameters are set.- Render: Blazor works out the HTML.
OnAfterRender/OnAfterRenderAsync: the HTML is now in the browser.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.
OnInitializeddoes 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.SetParametersAsyncline,Sizeis 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/masalato/tea/ginger, Blazor reuses the same page component. It does not create a new one. - So
OnInitializeddoes not run again. OnlyOnParametersSetruns. - Load data that depends on a route parameter in
OnParametersSet(Async), not inOnInitialized.
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
OnParametersSetprice changes to ₹25. TheOnInitializedprice 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
EventCallbackit 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 thoughsecondskeeps growing.
Render Control (ShouldRender)
ShouldRender()returnstrueorfalse. If it returnsfalse, 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.
@keygives 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 istrueonly 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
@implementstells the component to follow a specific interface, such asIDisposable.- It is the Razor equivalent of writing
: IDisposablein a C# class.
IDisposable
- Use
IDisposablewhen the component starts something that needs to be stopped later, such as a timer or event subscription. - Add
@implements IDisposableand create aDispose()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
@ifremovesTeaTimer, so Blazor callsDispose. The Console shows "Dispose: timer stopped".
IAsyncDisposable
- Use
IAsyncDisposablewhen cleanup requires an asynchronous operation, such as releasing a JavaScript object. - Add
@implements IAsyncDisposableand create aDisposeAsync()method.
Simple lesson: Stop timers and subscriptions in Dispose. Add @implements IDisposable to get it called.
Common mistakes
| Mistake | Wrong idea | Correct idea | What goes wrong |
|---|---|---|---|
Loading route data in OnInitialized | It runs on every page change | Use OnParametersSet(Async) | The page keeps the old data |
@foreach over data that is still loading | The data is there at the first render | Check for null first and show "Loading..." | An error on the first render |
Changing data in a timer without StateHasChanged | Blazor sees every change | Call InvokeAsync(StateHasChanged) | The page does not update |
StateHasChanged() in OnAfterRender without firstRender | It runs once | Wrap it in if (firstRender) | Renders forever |
A list that changes, without @key | Blazor matches items by value | Add @key to each item | Typed text jumps to another row |
A timer without Dispose | It stops when the page closes | @implements IDisposable and stop it | The timer keeps running |
Check Yourself
Exercises
What to Remember
- Order:
SetParametersAsync→OnInitialized(Async)(once) →OnParametersSet(Async)→ render →OnAfterRender(Async)→Dispose. - Load data in
OnInitializedAsync. Handlenullwhile it loads. - Work that depends on parameters, including route parameters, goes in
OnParametersSet(Async). - Call
StateHasChanged()for changes outside Blazor events, like timers.ShouldRendercan skip renders. - Use
@keyin lists that change. - Use
if (firstRender)inOnAfterRender. - Stop timers in
Disposewith@implements IDisposable.
Next: Layouts