Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 41 ยท Data Binding and Events

Component References and StateHasChanged

Learn when Blazor needs StateHasChanged, how InvokeAsync marshals work onto the UI thread, how to update from timers and background tasks, and how @ref gives you element and component references.

Most of the time Blazor re-renders for you: after an event handler runs, after parameters change, after a lifecycle method completes. But some changes happen outside these paths: a timer ticks, a message arrives from a background service, a long task reports progress. Then you have to tell Blazor "my state changed, please render" with StateHasChanged. This lesson also covers @ref, which lets you hold a reference to an element or a child component.

StateHasChanged

StateHasChanged() queues a render of the current component:

HTML
<p>Seconds: @seconds</p>

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

    protected override void OnInitialized()
    {
        timer = new Timer(_ =>
        {
            seconds++;
            StateHasChanged();       // wrong thread on Blazor Server: see below
        }, null, 1000, 1000);
    }
}

You do not need it after @onclick, @bind, or the end of OnInitializedAsync. You do need it when the change was made by code Blazor did not start: timers, events from services, Task.Run, SignalR hubs and file system watchers. It is also needed halfway through a long handler if you want to show intermediate progress, because a render normally only happens when control returns to Blazor at an await.

InvokeAsync and the sync context

Blazor components are not thread-safe. The renderer uses a synchronization context so only one piece of work touches component state at a time. A timer callback runs on a thread-pool thread, outside that context. Calling StateHasChanged from there throws errors like "The current thread is not associated with the Dispatcher". The fix is InvokeAsync, which marshals the work onto the right context:

C#
timer = new Timer(_ =>
{
    InvokeAsync(() =>
    {
        seconds++;
        StateHasChanged();
    });
}, null, 1000, 1000);

Rule: when you leave a Blazor-started code path (timer, event from a service, Task.Run), do await InvokeAsync(() => { change state; StateHasChanged(); }). Inside normal handlers and lifecycle methods you are already on the correct context.

Remember to stop the timer in Dispose (Component Lifecycle).

Progress and partial renders

During a long async handler, call StateHasChanged between steps:

C#
private async Task ImportAsync()
{
    for (int i = 1; i <= 5; i++)
    {
        await ProcessChunkAsync(i);
        progress = i * 20;
        StateHasChanged();          // show the new percentage now
    }
}

Without the call, the progress bar would only jump to 100% when the method returns. The await yields to the renderer, which gives the queued render a chance to run.

Subscribing to service events

The common pattern combines everything:

HTML
@implements IDisposable
@inject NotificationService Notifications

@code {
    protected override void OnInitialized() => Notifications.Changed += OnChanged;

    private void OnChanged() => InvokeAsync(StateHasChanged);

    public void Dispose() => Notifications.Changed -= OnChanged;
}

Subscribe in OnInitialized, render via InvokeAsync(StateHasChanged) and unsubscribe in Dispose. Forgetting the last step leaks components and causes updates to removed pages.

Component and element references: @ref

@ref captures a reference to an element or a child component in a field.

HTML
<input @ref="searchBox" placeholder="Search" />
<button @onclick="FocusSearch">Focus</button>

<Counter @ref="counter" />
<button @onclick="() => counter?.Reset()">Reset the counter</button>

@code {
    private ElementReference searchBox;
    private Counter? counter;

    private async Task FocusSearch() => await searchBox.FocusAsync();
}
  • For an HTML element, the field type is ElementReference. It is an opaque handle you can focus (FocusAsync()) or pass to JavaScript (JS interop). You cannot read its properties from C#.
  • For a component, the field type is the component class, and you may call its public methods, such as counter.Reset().
  • The reference is null until the first render has finished. Use it from event handlers or OnAfterRender, never from OnInitialized.

References are an escape hatch. Prefer parameters and callbacks for ordinary communication. Reach for @ref when you need an imperative action: set focus, scroll into view, reset a form or open a dialog.

Runnable stand-in: a render queue and the dispatcher

The stand-in below mimics the renderer: state changes are only visible after a render, renders are batched, and work coming from a background thread must be marshalled through a single-threaded "dispatcher". A TaskScheduler pins work to one thread so you can see the difference between marshalled and unmarshalled updates.

C# Stand-in: batching renders and marshalling

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The three StateHasChanged calls in the first handler produce a single render showing 60%, because renders are queued and processed when control returns to the framework. Each background update goes through the gate, so only one piece of work touches the state at a time.

Common mistakes

  • Calling StateHasChanged in every handler. It is automatic after @onclick and friends.
  • Calling it from a timer thread without InvokeAsync. You get a dispatcher exception on Blazor Server.
  • Never unsubscribing. Always pair += with -= in Dispose.
  • Using @ref too early. It is null until after the first render.
  • Blocking with .Result or .Wait(). This can deadlock the renderer; use await.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. When do you need to call StateHasChanged manually?

    Blazor re-renders automatically after its own events; outside them you must ask for a render.
  2. 2. What does InvokeAsync do?

    It marshals the work onto the renderer's context.
  3. 3. When is an @ref component field safe to use?

    References are assigned during rendering and are null before the first render completes.
  4. 4. A component subscribes to a service event in OnInitialized. What must it do in Dispose?

    Otherwise the service keeps the disposed component alive and keeps calling it.

Summary

  • Blazor renders automatically after its own events; use StateHasChanged for changes it did not start.
  • Use InvokeAsync from timers, services and Task.Run to run on the renderer's context.
  • Call StateHasChanged between awaits to show progress; always unsubscribe in Dispose.
  • @ref gives an ElementReference or a child component instance, available after the first render.

Next: EditForm Basics