Skip to content
Tutorials Center
My learning

Topics

Lesson 29 of 41 ยท State and Dependency Injection

Component State and Cascading Values

Learn how Blazor components keep state, when they re-render, how StateHasChanged works, and how CascadingValue and CascadingParameter share data down the component tree.

A Blazor component is a C# object that lives while it is on the screen. Its fields and properties are its state: a counter value, the text in a box, a loaded list. When state changes, the component must render again so the HTML matches. Understanding exactly when Blazor re-renders, and how to pass state from a parent down to many children without writing parameters at every level, is the center of the component model.

This lesson covers automatic re-rendering, StateHasChanged, the render lifecycle, [Parameter] flow, and CascadingValue, which makes a value available to every descendant. The framework syntax is read-only; the runnable stand-ins model the render cycle and the cascade with plain C#.

State lives in fields

RAZOR
<h2>Clicks: @count</h2>
<button @onclick="Increment">Add</button>

@code {
    private int count;

    private void Increment() => count++;
}

The @code block is the class body. count is just a private field: nothing special is needed to "make it reactive". After the @onclick handler finishes, Blazor re-renders the component, so the new number appears. The state survives as long as the component instance is alive: if the parent removes the component (an @if becomes false) the instance is discarded and the state is lost.

When does a component re-render?

Blazor re-renders a component when:

  1. A UI event handler it owns finishes (@onclick, @onchange, ...). The framework calls StateHasChanged for you after the handler, and again when an async handler awaits and completes its first synchronous part.
  2. Its parameters may have changed: a parent re-rendered and passed values.
  3. You call StateHasChanged() yourself.
  4. A cascading value it consumes changes.

It does not re-render just because you changed a field somewhere else, for example in a timer callback or a service event. That is the case that surprises people:

RAZOR
@implements IDisposable

<p>Seconds: @seconds</p>

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

    protected override void OnInitialized()
    {
        timer = new Timer(_ =>
        {
            seconds++;
            InvokeAsync(StateHasChanged);   // required: the callback is not a UI event
        }, null, 1000, 1000);
    }

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

Two points. A timer callback runs on a thread-pool thread, so use InvokeAsync(StateHasChanged) to switch back to the component's synchronization context; calling StateHasChanged() directly can throw. And dispose the timer: otherwise it keeps firing at a dead component.

The lifecycle in order

flowchart TB
    A["SetParametersAsync"] --> B["OnInitialized(Async)<br/>first time only"]
    B --> C["OnParametersSet(Async)"]
    C --> D["Render: build the tree"]
    D --> E["OnAfterRender(Async)<br/>firstRender flag"]
    E -->|"parameters or event"| C

Initialization runs once; parameters-set and render repeat for every change.

Use OnInitialized for one-time setup, OnParametersSet when a parameter drives the data, and OnAfterRender(firstRender) for work that needs the rendered DOM, such as calling JavaScript (see JavaScript Interop Basics). Do not change state in OnAfterRender without calling StateHasChanged and guarding against an endless loop.

The stand-in below mimics the cycle with a base class that owns StateHasChanged, a dirty flag and the lifecycle hooks, so you can print the exact order of calls.

C# Stand-in lifecycle and StateHasChanged

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.

Notice that the quiet field change leaves the displayed note stale until the next render shows both values.

Passing state down with parameters

A parent gives data to a child with [Parameter] properties:

RAZOR
@* Parent.razor *@
<UserBadge Name="@user.Name" Role="@user.Role" />
RAZOR
@* UserBadge.razor *@
<span>@Name (@Role)</span>

@code {
    [Parameter, EditorRequired] public string Name { get; set; } = "";
    [Parameter] public string Role { get; set; } = "guest";
}

Never assign to your own parameter properties inside the component: the parent's next render overwrites your change. If the child must change a value, expose an EventCallback<T> and let the parent update its state (that is the subject of the Data Binding chapter on @bind and callbacks).

Cascading values: skipping the middle layers

If a theme, the current user, or a form's edit context must reach components five levels deep, passing a parameter through every layer is tedious. A CascadingValue makes a value available to all descendants without intermediate involvement.

RAZOR
@* Provide *@
<CascadingValue Value="theme" Name="Theme">
    <Router ... />
</CascadingValue>

@code {
    private ThemeInfo theme = new() { Primary = "teal", Dark = false };
}
RAZOR
@* Consume anywhere below *@
<button style="background:@Theme.Primary">Save</button>

@code {
    [CascadingParameter(Name = "Theme")] private ThemeInfo Theme { get; set; } = default!;
}

Matching is by type (and by Name if you give one). Without names, two cascading values of the same type become ambiguous: the nearest ancestor wins. Use names for primitives like string or bool, and dedicated types for anything important.

Fixed values

By default, when a cascading value reference changes, Blazor re-renders every consumer. That is a cost on big trees. If the reference never changes (a stable object or a state container), set IsFixed="true": subscribers are not tracked and updates become cheaper. A fixed value can still change inside the object, but consumers will not be told, so combine it with events or StateHasChanged calls on the consumers.

Root-level cascading values

In Blazor Web Apps you can register one app-wide without markup, in Program.cs:

C#
builder.Services.AddCascadingValue(sp => new ThemeInfo { Primary = "teal" });

This is the cleanest way to provide a value to components in all render modes, because markup CascadingValue components do not cross a render mode boundary (an interactive island cannot see the value from a static parent).

A cascade in plain C#

The stand-in models a component tree where each node can see values from its ancestors. The lookup walks up the parents, by type, taking the nearest.

C# Stand-in cascading values

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.

Practical guidance

  • Keep state as local as possible. Lift it up only when two components need to share it.
  • Use cascading values for ambient, rarely-changing data (theme, auth state, edit context). Do not use them for frequently changing application data: use a state container, which is the next lesson.
  • A [CascadingParameter] whose provider is missing is null: guard it or give it a safe default.
  • Prefer [EditorRequired] on parameters a caller must supply; the compiler then warns when they are omitted.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A System.Threading.Timer callback changes a field. How do you make the UI update?

    The callback is not a UI event, so you must request a render, on the component's synchronization context.
  2. 2. Which lifecycle method runs only once per component instance?

    OnInitialized runs the first time parameters are set; the others repeat.
  3. 3. What is a CascadingValue best used for?

    Cascading values suit stable ambient data; frequently changing shared data fits a state container better.
  4. 4. What does IsFixed="true" on a CascadingValue do?

    A fixed value is not re-delivered to consumers, saving work when the reference is stable.

Summary

  • Component state is plain fields and properties; a render follows UI events, parameter changes, cascading changes and explicit StateHasChanged.
  • From non-UI callbacks use InvokeAsync(StateHasChanged) and remember to dispose timers and subscriptions.
  • The lifecycle: initialize once, set parameters and render repeatedly, then OnAfterRender.
  • CascadingValue and [CascadingParameter] pass ambient data through the tree by type or name.
  • Use IsFixed for stable references and AddCascadingValue for app-wide values.

Next: State Containers and App State