Blazor is an experimental web framework that is quickly evolving. Therefore, it is possible that some of the content on this blog post is already outdated.
Component instances have a lifecycle as Blazor creates, updates, and disposes of them. We can tap into key moments of the lifecycle via a series of methods, also known as lifecycle hooks. We can access them because Blazor components are derived from the
Microsoft.AspNetCore.Components.ComponentBase class. This class contains all the lifecycle methods that you can override easily for each component.
Lifecycle Sequence and Timing
Here you can see all the available lifecycle methods in the sequence they get called by Blazor.
|SetParametersAsync()||The first method invoked in the lifecycle before any parameter value is assigned to their respective properties. Also called each time new or updated parameters are received.|
|OnInit()||Invoked once, after every parameter value is received and assigned to their respective properties.|
|OnInitAsync()||Invoked once, after
|OnAfterRender()||Invoked after each render of the component. Called for the first time when the component is initialized and then after every re-render.|
|ShouldRender()||Invoked right before a component re-render is executed. Used to suppress current and future renders of the component.|
NOTELifecycle methods are always invoked at least once for every component. Even for components that don’t have parameters.
They Aren’t Shared… Wait, what?
Lifecycle methods are not shared between components. Meaning, you have a separate set of lifecycle methods for each component that won’t collide with other components. This gives you greater control over each of them throughout their lifetime. Pretty cool, right?
Lifecycle Methods In Action
Now that you know their sequence and timing, let’s learn a few more things about each method along with some examples to get an even better understanding.
This is the first method called in a component’s lifecycle. At this point, parameters are yet to be initialized. You can tap into each parameter, if any, and modify them before the component is rendered. Great for parameter validation!
In the following example, you’ll see the
SetParametersAsync method in action. To keep things simple, we only log the parameters received to the browser console.
The parent component is sending three parameters to the
<ParameterList> component: FirstName, LastName, and Age. They were also bound to separate input fields to update their value and have the
SetParametersAsync method trigger again on the child component.
In the child component, we are iterating over the
ParameterCollection object whenever a parameter gets a new or updated value from the parent component.
OnInit() and OnInitAsync()
These methods are called when the component is ready to start. At this point, initial parameter values are already available in their respective properties. Use
OnInitAsync and the
await keyword for any asynchronous operations.
OnInitAsynctriggers a component refresh when it is done executing.
Let’s now look at an example where both methods are used to modify the value of a parameter.
We are using the
OnInit method to initialize the Title parameter if no value is passed from a parent component. Then we change its value again with
OnInitAsync after three seconds. This way you’ll see that the component gets re-rendered when
OnInitAsync has finished executing. We also added a button to change the Title value to show that the app is functional while the
OnInitAsync method is running.
OnParametersSet() and OnParametersSetAsync()
By the time these methods are called, all parameters have been assigned to their respective properties. They both get executed for the first time on component initialization, right after
OnInit, and then each time parameter values are updated by the parent component.
OnParametersSetAsynctriggers a component refresh when it is done executing.
In the following example, the parent component is sending a random number to the child component when the Generate number button is clicked. This, in turn, triggers a call to the
OnParametersSetAsync methods on the child component.
In the child component, we have a table displaying three things: the number of times the
OnParametersSet has been called, the random number received by the parent component, and the same random number getting updated by the
OnParametersSetAsync after one second.
In the output, you’ll notice that the
OnParametersSet method is called once when the component is initialized and then each time the RandNum parameter receives a new value.
OnAfterRender() and OnAfterRenderAsync()
NOTENever call the StateHasChanged method inside of
OnAfterRenderAsyncunless you have a good reason because it can cause an endless loop.
In this component, we use the
OnAfterRender method to write a message to the console every time it gets invoked.
There are a few more files you will need to run this example:
You can get all of them from our GitHub page: nativoplus/BlazorWorkshop
In the console window you can see two messages: the first one is from our
This method returns a
boolean value. If the value is
true, the UI is re-rendered. But even if you override this method, the component will still render once when initialized. Use this to suppress subsequent rendering of the component. Let’s look at an example.
In the following example, a simple counter component is used to trigger a UI refresh when the value
count changes. This way, the
ShouldRender method gets invoked and we can use it to suppress further rendering.
See how easily it is to suppress further rendering of a component with the click of a button! And turn it back on whenever we want to. Also, notice how the Increment button still works even when rendering is turned off, we can see how much the counter has increased by turning it back on.
These methods aren’t part of the Blazor component lifecycle but they are very useful at different steps of the lifecycle process.
This method is called to indicate that the state of a component has changed. Therefore, Blazor re-renders the calling component. This method can’t be overridden but it can be triggered manually.
Easily use it inside any of your components with the
StateHasChangedonly triggers a UI refresh for the current component. It does not automatically refresh child or parent components.
Your Blazor components can implement the
IDisposable interface. If you do, the
Dispose method is available for you to override. This method gets called whenever the calling component is removed from the UI.
Just add the
IDisposible interface to your component and implement the
Dispose method like this:
Blazor provides a number of lifecycle methods that you can easily override. This allows you to execute additional operations at key moments of a component’s lifecycle. Also, most lifecycle methods conveniently have an asynchronous counterpart that you can use for operations that might take a long time to execute. Finally, we saw a couple of methods,
Dispose, that aren’t part of a component’s lifecycle but can be quite useful at different times of the lifecycle process.
You can get all the examples shown on this post from our GitHub page: nativoplus/BlazorWorkshop