ASP.NET Core Razor component rendering
This article explains Razor component rendering in ASP.NET Core Blazor apps, including when to call StateHasChanged to manually trigger a component to render.
Components must render when they're first added to the component hierarchy by a parent component. This is the only time that a component must render. Components may render at other times according to their own logic and conventions.
Rendering conventions for ComponentBase
By default, Razor components inherit from the ComponentBase base class, which contains logic to trigger rerendering at the following times:
- After applying an updated set of parameters from a parent component.
- After applying an updated value for a cascading parameter.
- After notification of an event and invoking one of its own event handlers.
- After a call to its own StateHasChanged method (see ASP.NET Core Razor component lifecycle). For guidance on how to prevent overwriting child component parameters when StateHasChanged is called in a parent component, see ASP.NET Core Razor components.
Components inherited from ComponentBase skip rerenders due to parameter updates if either of the following are true:
All of the parameters are from a set of known types† or any primitive type that hasn't changed since the previous set of parameters were set.
†The Blazor framework uses a set of built-in rules and explicit parameter type checks for change detection. These rules and the types are subject to change at any time. For more information, see the
ChangeDetection
API in the ASP.NET Core reference source.Note
Documentation links to .NET reference source usually load the repository's default branch, which represents the current development for the next release of .NET. To select a tag for a specific release, use the Switch branches or tags dropdown list. For more information, see How to select a version tag of ASP.NET Core source code (dotnet/AspNetCore.Docs #26205).
The component's
ShouldRender
method returnsfalse
.
Control the rendering flow
In most cases, ComponentBase conventions result in the correct subset of component rerenders after an event occurs. Developers aren't usually required to provide manual logic to tell the framework which components to rerender and when to rerender them. The overall effect of the framework's conventions is that the component receiving an event rerenders itself, which recursively triggers rerendering of descendant components whose parameter values may have changed.
For more information on the performance implications of the framework's conventions and how to optimize an app's component hierarchy for rendering, see ASP.NET Core Blazor performance best practices.
Suppress UI refreshing (ShouldRender
)
ShouldRender is called each time a component is rendered. Override ShouldRender to manage UI refreshing. If the implementation returns true
, the UI is refreshed.
Even if ShouldRender is overridden, the component is always initially rendered.
Pages/ControlRender.razor
:
@page "/control-render"
<label>
<input type="checkbox" @bind="shouldRender" />
Should Render?
</label>
<p>Current count: @currentCount</p>
<p>
<button @onclick="IncrementCount">Click me</button>
</p>
@code {
private int currentCount = 0;
private bool shouldRender = true;
protected override bool ShouldRender()
{
return shouldRender;
}
private void IncrementCount()
{
currentCount++;
}
}
@page "/control-render"
<label>
<input type="checkbox" @bind="shouldRender" />
Should Render?
</label>
<p>Current count: @currentCount</p>
<p>
<button @onclick="IncrementCount">Click me</button>
</p>
@code {
private int currentCount = 0;
private bool shouldRender = true;
protected override bool ShouldRender()
{
return shouldRender;
}
private void IncrementCount()
{
currentCount++;
}
}
@page "/control-render"
<label>
<input type="checkbox" @bind="shouldRender" />
Should Render?
</label>
<p>Current count: @currentCount</p>
<p>
<button @onclick="IncrementCount">Click me</button>
</p>
@code {
private int currentCount = 0;
private bool shouldRender = true;
protected override bool ShouldRender()
{
return shouldRender;
}
private void IncrementCount()
{
currentCount++;
}
}
@page "/control-render"
<label>
<input type="checkbox" @bind="shouldRender" />
Should Render?
</label>
<p>Current count: @currentCount</p>
<p>
<button @onclick="IncrementCount">Click me</button>
</p>
@code {
private int currentCount = 0;
private bool shouldRender = true;
protected override bool ShouldRender()
{
return shouldRender;
}
private void IncrementCount()
{
currentCount++;
}
}
For more information on performance best practices pertaining to ShouldRender, see ASP.NET Core Blazor performance best practices.
When to call StateHasChanged
Calling StateHasChanged allows you to trigger a render at any time. However, be careful not to call StateHasChanged unnecessarily, which is a common mistake that imposes unnecessary rendering costs.
Code shouldn't need to call StateHasChanged when:
- Routinely handling events, whether synchronously or asynchronously, since ComponentBase triggers a render for most routine event handlers.
- Implementing typical lifecycle logic, such as
OnInitialized
orOnParametersSetAsync
, whether synchronously or asynchronously, since ComponentBase triggers a render for typical lifecycle events.
However, it might make sense to call StateHasChanged in the cases described in the following sections of this article:
- An asynchronous handler involves multiple asynchronous phases
- Receiving a call from something external to the Blazor rendering and event handling system
- To render component outside the subtree that is rerendered by a particular event
An asynchronous handler involves multiple asynchronous phases
Due to the way that tasks are defined in .NET, a receiver of a Task can only observe its final completion, not intermediate asynchronous states. Therefore, ComponentBase can only trigger rerendering when the Task is first returned and when the Task finally completes. The framework can't know to rerender a component at other intermediate points, such as when an IAsyncEnumerable<T> returns data in a series of intermediate Task
s. If you want to rerender at intermediate points, call StateHasChanged at those points.
Consider the following CounterState1
component, which updates the count four times on each click:
- Automatic renders occur after the first and last increments of
currentCount
. - Manual renders are triggered by calls to StateHasChanged when the framework doesn't automatically trigger rerenders at intermediate processing points where
currentCount
is incremented.
Pages/CounterState1.razor
:
@page "/counter-state-1"
<p>
Current count: @currentCount
</p>
<p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
</p>
@code {
private int currentCount = 0;
private async Task IncrementCount()
{
currentCount++;
// Renders here automatically
await Task.Delay(1000);
currentCount++;
StateHasChanged();
await Task.Delay(1000);
currentCount++;
StateHasChanged();
await Task.Delay(1000);
currentCount++;
// Renders here automatically
}
}
@page "/counter-state-1"
<p>
Current count: @currentCount
</p>
<p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
</p>
@code {
private int currentCount = 0;
private async Task IncrementCount()
{
currentCount++;
// Renders here automatically
await Task.Delay(1000);
currentCount++;
StateHasChanged();
await Task.Delay(1000);
currentCount++;
StateHasChanged();
await Task.Delay(1000);
currentCount++;
// Renders here automatically
}
}
@page "/counter-state-1"
<p>
Current count: @currentCount
</p>
<p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
</p>
@code {
private int currentCount = 0;
private async Task IncrementCount()
{
currentCount++;
// Renders here automatically
await Task.Delay(1000);
currentCount++;
StateHasChanged();
await Task.Delay(1000);
currentCount++;
StateHasChanged();
await Task.Delay(1000);
currentCount++;
// Renders here automatically
}
}
@page "/counter-state-1"
<p>
Current count: @currentCount
</p>
<p>
<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>
</p>
@code {
private int currentCount = 0;
private async Task IncrementCount()
{
currentCount++;
// Renders here automatically
await Task.Delay(1000);
currentCount++;
StateHasChanged();
await Task.Delay(1000);
currentCount++;
StateHasChanged();
await Task.Delay(1000);
currentCount++;
// Renders here automatically
}
}
Receiving a call from something external to the Blazor rendering and event handling system
ComponentBase only knows about its own lifecycle methods and Blazor-triggered events. ComponentBase doesn't know about other events that may occur in code. For example, any C# events raised by a custom data store are unknown to Blazor. In order for such events to trigger rerendering to display updated values in the UI, call StateHasChanged.
Consider the following CounterState2
component that uses System.Timers.Timer to update a count at a regular interval and calls StateHasChanged to update the UI:
OnTimerCallback
runs outside of any Blazor-managed rendering flow or event notification. Therefore,OnTimerCallback
must call StateHasChanged because Blazor isn't aware of the changes tocurrentCount
in the callback.- The component implements IDisposable, where the Timer is disposed when the framework calls the
Dispose
method. For more information, see ASP.NET Core Razor component lifecycle.
Because the callback is invoked outside of Blazor's synchronization context, the component must wrap the logic of OnTimerCallback
in ComponentBase.InvokeAsync to move it onto the renderer's synchronization context. This is equivalent to marshalling to the UI thread in other UI frameworks. StateHasChanged can only be called from the renderer's synchronization context and throws an exception otherwise:
System.InvalidOperationException: 'The current thread is not associated with the Dispatcher. Use InvokeAsync() to switch execution to the Dispatcher when triggering rendering or component state.'
Pages/CounterState2.razor
:
@page "/counter-state-2"
@using System.Timers
@implements IDisposable
<h1>Counter with <code>Timer</code> disposal</h1>
<p>
Current count: @currentCount
</p>
@code {
private int currentCount = 0;
private Timer timer = new(1000);
protected override void OnInitialized()
{
timer.Elapsed += (sender, eventArgs) => OnTimerCallback();
timer.Start();
}
private void OnTimerCallback()
{
_ = InvokeAsync(() =>
{
currentCount++;
StateHasChanged();
});
}
public void Dispose() => timer.Dispose();
}
@page "/counter-state-2"
@using System.Timers
@implements IDisposable
<h1>Counter with <code>Timer</code> disposal</h1>
<p>
Current count: @currentCount
</p>
@code {
private int currentCount = 0;
private Timer timer = new(1000);
protected override void OnInitialized()
{
timer.Elapsed += (sender, eventArgs) => OnTimerCallback();
timer.Start();
}
private void OnTimerCallback()
{
_ = InvokeAsync(() =>
{
currentCount++;
StateHasChanged();
});
}
public void Dispose() => timer.Dispose();
}
@page "/counter-state-2"
@using System.Timers
@implements IDisposable
<h1>Counter with <code>Timer</code> disposal</h1>
<p>
Current count: @currentCount
</p>
@code {
private int currentCount = 0;
private Timer timer = new(1000);
protected override void OnInitialized()
{
timer.Elapsed += (sender, eventArgs) => OnTimerCallback();
timer.Start();
}
private void OnTimerCallback()
{
_ = InvokeAsync(() =>
{
currentCount++;
StateHasChanged();
});
}
public void Dispose() => timer.Dispose();
}
@page "/counter-state-2"
@using System.Timers
@implements IDisposable
<h1>Counter with <code>Timer</code> disposal</h1>
<p>
Current count: @currentCount
</p>
@code {
private int currentCount = 0;
private Timer timer = new Timer(1000);
protected override void OnInitialized()
{
timer.Elapsed += (sender, eventArgs) => OnTimerCallback();
timer.Start();
}
private void OnTimerCallback()
{
_ = InvokeAsync(() =>
{
currentCount++;
StateHasChanged();
});
}
public void Dispose() => timer.Dispose();
}
To render a component outside the subtree that's rerendered by a particular event
The UI might involve:
- Dispatching an event to one component.
- Changing some state.
- Rerendering a completely different component that isn't a descendant of the component receiving the event.
One way to deal with this scenario is to provide a state management class, often as a dependency injection (DI) service, injected into multiple components. When one component calls a method on the state manager, the state manager raises a C# event that's then received by an independent component.
For approaches to manage state, see the following resources:
- In-memory state container service (Blazor Server) (Blazor WebAssembly equivalent) section of the State management article.
- Pass data across a component hierarchy using cascading values and parameters.
- Bind across more than two components using data bindings.
For the state manager approach, C# events are outside the Blazor rendering pipeline. Call StateHasChanged on other components you wish to rerender in response to the state manager's events.
The state manager approach is similar to the earlier case with System.Timers.Timer in the previous section. Since the execution call stack typically remains on the renderer's synchronization context, calling InvokeAsync isn't normally required. Calling InvokeAsync is only required if the logic escapes the synchronization context, such as calling ContinueWith on a Task or awaiting a Task with ConfigureAwait(false)
. For more information, see the Receiving a call from something external to the Blazor rendering and event handling system section.
Feedback
Submit and view feedback for