StateHasChanged in Blazor: Why Your Component Is Not Refreshing

My first live-orders page in Blazor used a timer to add an online order every second. The console counted up, but the page never refreshed. Adding StateHasChanged() to the timer then crashed the whole app.

That’s the classic Blazor StateHasChanged not refreshing trap: Blazor re-renders on its own only after its own events and lifecycle methods.

Quick answer: call StateHasChanged() for changes Blazor can’t see, wrapped in InvokeAsync when the code runs off Blazor’s thread. Below are seven real cases on .NET 10.

When Does Blazor Re-render a Component Automatically?

A component that inherits ComponentBase re-renders on its own only in the cases on the left (per Microsoft Learn), the same points you see in the Blazor component lifecycle:

Re-renders automaticallyNeeds StateHasChanged()
After one of its own event handlers (@onclick, @bind)Timer callbacks
After its lifecycle methods (OnInitializedAsync, …)C# events raised by a service
After the parent passes new parametersA sibling or parent whose data changed
After a cascading value changesProgress in the middle of an async handler

An async Task handler gets two automatic renders: when the task is first returned and when it completes.

Set Up the StateHasChanged Demo App

I used the .NET 10 SDK (10.0.402) and the Blazor Web App template. If the template is new to you, my Blazor tutorial for beginners walks through it.

dotnet new blazor -o W12StateHas

I deleted appsettings.Development.json and kept the template’s appsettings.json and project file, plus a plain http launch profile on port 5902:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}
<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>net10.0</TargetFramework>
    <Nullable>enable</Nullable>
    <ImplicitUsings>enable</ImplicitUsings>
    <BlazorDisableThrowNavigationException>true</BlazorDisableThrowNavigationException>
  </PropertyGroup>

</Project>
{
  "$schema": "https://json.schemastore.org/launchsettings.json",
  "profiles": {
    "http": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": false,
      "applicationUrl": "http://localhost:5902",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}

Program.cs registers a cart service as scoped (one per circuit, see DI lifetimes) and drops the https redirect:

using W12StateHas.Components;
using W12StateHas.Services;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddScoped<CartState>();   // one cart per circuit

builder.Services.AddRazorComponents()
    .AddInteractiveServerComponents();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error", createScopeForErrors: true);
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}
app.UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: true);

app.UseAntiforgery();

app.MapStaticAssets();
app.MapRazorComponents<App>()
    .AddInteractiveServerRenderMode();

app.Run();

Why Is My Blazor Component Not Refreshing After a Timer Tick?

Here’s the page that started it, LiveOrders.razor. A System.Threading.Timer adds an order every second, starting after the first interactive render:


@page "/live-orders"
@rendermode InteractiveServer
@implements IDisposable

<PageTitle>Live Orders</PageTitle>

<h1>Harbor Lane Bakery - Live Orders</h1>
<p class="fs-4">Online orders today: <strong id="count">@ordersToday</strong></p>

@code {
    private int ordersToday;
    private Timer? timer;

    protected override void OnAfterRender(bool firstRender)
    {
        if (firstRender)
            timer = new Timer(_ => OnNewOrder(), null, 1000, 1000);
    }

    private void OnNewOrder()
    {
        ordersToday++;
        Console.WriteLine($"Timer tick: ordersToday = {ordersToday}");
    }

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

I opened the page in Edge and waited 5.5 seconds. The server console counted every tick:

Timer tick: ordersToday = 1
Timer tick: ordersToday = 2
Timer tick: ordersToday = 3
Timer tick: ordersToday = 4
Timer tick: ordersToday = 5
Blazor Live Orders page in Edge still showing Online orders today: 0 while a System.Threading.Timer has already incremented the field
The field changed on the server, but the page still shows 0

The field kept climbing (it hit 11 before I stopped the server), but the page showed 0. A timer isn’t a Blazor event, so nothing asked for a render.

StateHasChanged From a Timer Throws a Dispatcher Exception

The obvious fix is one line at the end of OnNewOrder:

    private void OnNewOrder()
    {
        ordersToday++;
        Console.WriteLine($"Timer tick: ordersToday = {ordersToday}");
        StateHasChanged();   // called from a thread-pool thread
    }

The first tick killed the app. The terminal showed this, then the server process exited:

Unhandled exception. 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.
VS Code with LiveOrders.razor open and the dotnet run terminal showing Unhandled exception System.InvalidOperationException The current thread is not associated with the Dispatcher
StateHasChanged() from the timer thread: unhandled InvalidOperationException

StateHasChanged can only run on the renderer’s synchronization context. A System.Threading.Timer callback runs on a thread-pool thread, and an unhandled exception there ends the whole process, so every connected user loses the app.

Fix It With InvokeAsync(StateHasChanged)

InvokeAsync takes a delegate and runs it on Blazor’s dispatcher. I moved the field update inside it too, so it can’t race with a render:

    private void OnNewOrder() => _ = InvokeAsync(() =>
    {
        ordersToday++;
        Console.WriteLine($"Timer tick: ordersToday = {ordersToday}");
        StateHasChanged();
    });
Blazor Live Orders page in Edge showing the online order count going up after the timer callback calls InvokeAsync with StateHasChanged
With InvokeAsync, every tick shows up on the page

Now the page kept up: it read 5 at 5.5 seconds and kept climbing. Keep the Dispose method: it stops the timer when the user leaves the page. For timers you await, a PeriodicTimer plus a CancellationToken is the cleaner pattern.

Refresh Another Component With a State Container Event

The second bug was a cart badge. A menu item adds to a shared CartState service, and a badge in the heading shows the count:

namespace W12StateHas.Services;

public class CartState
{
    private readonly List<string> items = [];

    public IReadOnlyList<string> Items => items;

    public event Action? OnChange;

    public void Add(string item)
    {
        items.Add(item);
        Console.WriteLine($"CartState.Add: {item} ({items.Count} items)");
        OnChange?.Invoke();
    }
}

@using System.Globalization
@using W12StateHas.Services
@inject CartState Cart

<div class="card mb-2" style="max-width: 26rem;">
    <div class="card-body py-2 d-flex justify-content-between align-items-center">
        <span>@Name - @Price.ToString("C", Us) @(added > 0 ? $"(added {added})" : "")</span>
        <button class="btn btn-sm btn-outline-primary" data-item="@Name" @onclick="Add">Add</button>
    </div>
</div>

@code {
    private static readonly CultureInfo Us = new("en-US");
    private int added;

    [Parameter] public string Name { get; set; } = "";
    [Parameter] public decimal Price { get; set; }

    private void Add()
    {
        added++;
        Cart.Add(Name);
    }
}

@page "/menu"
@rendermode InteractiveServer

<PageTitle>Menu</PageTitle>

<h1>Harbor Lane Bakery <CartBadge /></h1>

<MenuItem Name="Blueberry muffin" Price="3.75m" />
<MenuItem Name="Maple scone" Price="4.25m" />
<MenuItem Name="Sourdough loaf" Price="8.50m" />

The first CartBadge.razor just read the count:


@using W12StateHas.Services
@inject CartState Cart

<span class="badge bg-primary fs-6 ms-2">Cart: @Cart.Items.Count</span>

I clicked Add on the muffin and the scone. Each item showed “(added 1)”, the console logged 2 items, and the badge stayed at 0. The click re-rendered only the MenuItem that received it; the badge isn’t its child.

Before and after in Edge: the Blazor cart badge stays at Cart: 0 after two Add clicks, then shows Cart: 2 once CartBadge subscribes to the OnChange event
Left: the badge doesn’t refresh. Right: the badge subscribed to CartState.OnChange

The fix is to subscribe to the service’s C# event and unsubscribe in Dispose:


@using W12StateHas.Services
@implements IDisposable
@inject CartState Cart

<span class="badge bg-primary fs-6 ms-2">Cart: @Cart.Items.Count</span>

@code {
    protected override void OnInitialized() => Cart.OnChange += Refresh;

    private void Refresh() => _ = InvokeAsync(StateHasChanged);

    public void Dispose()
    {
        Cart.OnChange -= Refresh;
        Console.WriteLine($"CartBadge.Dispose ({RendererInfo.Name}): unsubscribed");
    }
}

This time I added both items and then clicked the W12StateHas home link:

CartBadge.Dispose (Static): unsubscribed
CartState.Add: Blueberry muffin (1 items)
CartState.Add: Maple scone (2 items)
CartBadge.Dispose (Server): unsubscribed
VS Code with CartBadge.razor open and the terminal showing CartState.Add for two items and CartBadge.Dispose unsubscribed when the user leaves the menu page
The badge refreshes, and Dispose removes the handler when the page goes away

The (Static) line is the discarded prerendered copy. Skip the -= and the service holds every dead badge, the leak the Dispose pattern prevents.

Why Doesn’t the Parent Component Refresh When a Child Changes Data?

Same root cause, other direction. Pickups.razor shows a count, and each ReadyButton child reports back through an Action<string> parameter:


@page "/pickups"
@rendermode InteractiveServer

<PageTitle>Pickups</PageTitle>

<h1>Ready for pickup: @ready.Count</h1>
<p>@(ready.Count == 0 ? "No orders yet" : string.Join(", ", ready))</p>

<ReadyButton OrderNumber="#1043" OnReady="AddReady" />
<ReadyButton OrderNumber="#1044" OnReady="AddReady" />

@code {
    private readonly List<string> ready = [];

    private void AddReady(string order)
    {
        ready.Add(order);
        Console.WriteLine($"Pickups.AddReady: {order} ({ready.Count} ready)");
    }
}

<button class="btn btn-success me-2" data-order="@OrderNumber" disabled="@done" @onclick="MarkReady">
    @(done ? $"{OrderNumber} marked" : $"Mark {OrderNumber} ready")
</button>

@code {
    private bool done;

    [Parameter] public string OrderNumber { get; set; } = "";
    [Parameter] public Action<string>? OnReady { get; set; }

    private void MarkReady()
    {
        done = true;
        OnReady?.Invoke(OrderNumber);
    }
}

Two clicks: the console said Pickups.AddReady: #1044 (2 ready), both buttons switched to “marked”, and the heading still said 0. The parent’s method ran, but the event belonged to the child.

Change the parameter to EventCallback<string>. Blazor then re-renders the parent after the callback, no StateHasChanged needed:

    [Parameter] public EventCallback<string> OnReady { get; set; }

    private async Task MarkReady()
    {
        done = true;
        await OnReady.InvokeAsync(OrderNumber);
    }
Before and after in Edge: Ready for pickup: 0 with an Action parameter, Ready for pickup: 2 after switching the child parameter to EventCallback
Left: Action. Right: EventCallback refreshes the parent

The parent markup didn’t change. My Blazor components guide covers parameters in depth.

StateHasChanged Inside a Loop: Show Progress From an Async Handler

Import.razor saves five orders, 600 ms each. Without the StateHasChanged() line in the loop, the page showed “Idle” at 2.1 seconds and jumped straight to “Done: 5 orders imported” at the end:


@page "/import"
@rendermode InteractiveServer

<PageTitle>Import</PageTitle>

<h1>Import Orders</h1>
<p class="fs-5">Status: <strong id="status">@status</strong></p>
<button class="btn btn-primary" id="import" @onclick="ImportAsync">Import 5 orders</button>
<button class="btn btn-outline-secondary" id="total" @onclick="LoadTotal">Load today's total</button>

@code {
    private string status = "Idle";

    private async Task ImportAsync()
    {
        for (int i = 1; i <= 5; i++)
        {
            await Task.Delay(600);   // stands in for saving one order
            status = $"Imported {i} of 5";
            StateHasChanged();       // render the progress now
        }
        status = "Done: 5 orders imported";
    }

    private async void LoadTotal()
    {
        status = "Loading total...";
        await Task.Delay(500);
        status = "Total today: $1,284.50";
    }
}
Before and after in Edge at 2.1 seconds into the import: Status Idle without StateHasChanged in the loop, Imported 4 of 5 with it
Same moment, with and without StateHasChanged() in the loop

With the line, the same moment read “Imported 4 of 5”. Each await gives the renderer a chance to draw what StateHasChanged queued. Five calls with no await between them still render once.

async void Event Handlers Stop Blazor From Refreshing

The second button on that page is async void LoadTotal(). One click, 1.5 seconds later, and the status still read “Loading total…”. Blazor rendered after the synchronous part and had no task to wait for, so the final value never reached the page.

Changing the signature to async Task fixed it with no other change: the page showed “Total today: $1,284.50”.

    private async Task LoadTotal()

Note: an exception in an async void method also skips Blazor’s error handling.

ShouldRender and Static Render Mode Block StateHasChanged

If StateHasChanged runs and nothing happens, check for a ShouldRender override. When it returns false, Blazor skips the render (only the very first render is guaranteed):

protected override bool ShouldRender() => shouldRender;

The other blocker is render mode. I removed @rendermode InteractiveServer from the template’s Counter page and clicked the button three times: it still said “Current count: 0”, since static SSR has no circuit and runs no handlers. My Blazor render modes guide covers the options.

Infinite Render Loop: StateHasChanged in OnAfterRender

OnAfterRender runs after every render, so calling StateHasChanged there unconditionally queues another render, forever. The method in RenderLoop.razor:

protected override void OnAfterRender(bool firstRender)
{
        renders++;
        if (renders % 2000 == 0)
            Console.WriteLine($"OnAfterRender call #{renders}");
        StateHasChanged();   // BUG: every render queues another render
}

About a second after the circuit connected, the page said “Renders: 2325” and the console was still counting:

VS Code with RenderLoop.razor open and the terminal printing OnAfterRender call numbers in the thousands from a StateHasChanged call inside OnAfterRender
StateHasChanged() in OnAfterRender: thousands of renders in seconds

Guard it with firstRender, the same check you use for JavaScript interop setup:

        renders++;
        Console.WriteLine($"OnAfterRender call #{renders}");
        if (firstRender)
            StateHasChanged();   // one extra render, then it stops

Now the log shows OnAfterRender call #1 and OnAfterRender call #2, then stops. Microsoft Learn notes that a task returned from OnAfterRenderAsync never triggers a render either, for this exact reason.

Which StateHasChanged Fix Do You Need?

SymptomFix
Timer, Task.Run or background work changes a fieldInvokeAsync(StateHasChanged)
“The current thread is not associated with the Dispatcher”Same: wrap the update in InvokeAsync
A sibling component doesn’t updateService event + StateHasChanged, unsubscribe in Dispose
Parent doesn’t update after a child changeEventCallback<T> instead of Action<T>
Progress only shows at the endStateHasChanged() after each await
Final value never showsasync Task, never async void
Buttons do nothingAdd an interactive render mode

Regular event handlers and form submits need none of this; extra calls only cost renders.

If you’re building more Blazor pages, these are good next reads:

Frequently Asked Questions

Why is StateHasChanged not refreshing my Blazor component?

Usually one of four things: the call runs off Blazor’s dispatcher (use InvokeAsync), a different component needs the refresh, ShouldRender returns false, or the page has no interactive render mode. See ASP.NET Core Razor component rendering on Microsoft Learn.

What is the difference between StateHasChanged and InvokeAsync(StateHasChanged)?

StateHasChanged queues a render and must run on the renderer’s synchronization context. InvokeAsync first switches to that context, so InvokeAsync(StateHasChanged) is safe from timers, Task.Run and service events raised on other threads.

How do I refresh a child component in Blazor?

Pass it new parameter values from the parent; the child re-renders when they change. For a component that isn’t a child, use a shared state service with an event the component subscribes to.

How do I refresh the whole page in Blazor?

Call NavigationManager.Refresh() (.NET 8 and later). Refresh(forceReload: true) always does a full reload; otherwise the new HTML may be merged into the current page.

Why do I get “The current thread is not associated with the Dispatcher”?

You called StateHasChanged, or changed rendered state, from a thread Blazor doesn’t own. Wrap the code in InvokeAsync, as the Blazor synchronization context docs show.